功能:小程序端实现微信上传,并将图片转换成byte字节流数组存入oracle的blob字段中。
图片上传功能包括图片的选择、预览、删除。(暂未做上传成功的提示)预览效果如下:
小程序端代码(代码中包括一些页面的其他代码):
WXML:
<view class="page">
<view class="page__bd">
<view class="page__bd page__bd_spacing">
<view class="kind-list">
<block>
<view class="kind-list__item up-down">
<view class="weui-flex left-right">
<view class="" style='width:40%;margin-left:40rpx'>当前巡视</view>
<view class="" style='width:60%;'>
<input class="weui-input" placeholder="怀密一二" disabled='disabled' />
</view>
</view>
<view class="weui-flex left-right" wx:if="{{major == '输电架空' || major == '输电通道'}}">
<view class="" style='width:40%;margin-left:40rpx'>当前杆塔</view>
<view class="" style='width:60%;'>
<input class="weui-input" placeholder="输入杆塔号" />
</view>
</view>
<view class="weui-flex left-right" wx:if="{{major != '输电架空' && major != '输电通道' && arraylength != 1}}">
<view class="" style='width:40%;margin-left:40rpx'>设备类型</view>
<view class="" style='width:50%;'>
<picker bindchange="bindPickerChange" value="{{index}}" range="{{array}}">
<input class="weui-input" value='{{array[index]}}' />
</picker>
</view>
<view class="" style='width:10%;'>
<image class="img_size-sm" src="../../../icons/rightjt.png"></image>
</view>
</view>
</view>
</block>
</view>
</view>
</view>
<scroll-view scroll-y="true" style="height: 80vh">
<view class="page__bd page__bd_spacing">
<view class="kind-list">
<block wx:for="{{list}}" wx:key="id">
<view class="kind-list__item">
<view id="{{item.id}}" class="weui-flex kind-list__item-hd {{item.open ? 'kind-list__item-hd_show' : ''}}" bindtap="kindToggle">
<view data-id="{{item.id}}" wx:if="{{item.finish}}" class="img_size-m">
<image class="img_size-m" style='margin-left:-10px;' src="../../../icons/finish.png"></image>
</view>
<view class="weui-flex__item">{{item.content}}</view>
<image class="kind-list__img" src="../../../icons/icon_nav_form.png"></image>
</view>
<view class="kind-list__item-bd {{item.open ? 'kind-list__item-bd_show' : ''}}">
<view class="weui-cells {{item.open ? 'weui-cells_show' : ''}}">
<block>
<view class="weui-cell weui-cell_access">
<view class='up-down' style='width:100%'>
<view class='left-right text_left'>
<view style='width:100vw'>
<button type="default" bindtap='criterionInfo' data-statu="open" data-id="{{item.id}}">巡视标准</button>
</view>
</view>
<view style='margin-top:30rpx'>
<view class="weui-cell">
<view class="weui-cell__bd">
<view class="weui-uploader">
<view class="weui-uploader__hd">
<view class="weui-uploader__title">图片上传</view>
<view class="weui-uploader__info">{{item.imageList.length}}/3</view>
</view>
<view class="weui-uploader__bd">
<view class="weui-uploader__files">
<block wx:for="{{item.imageList}}" wx:key="">
<view class="weui-uploader__file" style='position: relative;margin-top:9px;'>
<image class="weui-uploader__img" src="{{item}}" data-src="{{image}}" data-index="{{index}}" bindtap="previewImage" data-id='{{item.id}}'></image>
<view class="weui-badge" data-index="{{index}}" style="position: absolute;top: -.4em;right: -.4em;" bindtap='deleteImage'>X</view>
</view>
</block>
</view>
<view class="weui-uploader__input-box" style='margin-top:9px;' wx:if="{{item.imageList.length<3}}">
<view class="weui-uploader__input" data-id='{{item.id}}' bindtap="chooseImage"></view>
</view>
</view>
</view>
</view>
</view>
</view>
<view>
<button data-id='{{item.id}}' class="weui-btn" style='margin-top:30rpx' type="primary" bindtap="uploadFile">提交</button>
</view>
</view>
</view>
</block>
</view>
</view>
</view>
</block>
</view>
</view>
</scroll-view>
</view>
<view bindtap='patrolFinish'>
<image class="img_size-l add_icon" src="../../../icons/finishImg.png"></image>
</view>
<modal hidden="{{hiddenmodalput}}" title="巡视标准" confirm-text="确定" no-cancel="false" bindcancel="cancelM" bindconfirm="confirmM">
<scroll-view scroll-y="true" style='height:450rpx'>
<view class="weui-article__p" style='text-align:left'>
<text>{{patrolInfo}}</text>
</view>
</scroll-view>
</modal>
JS:
var app = getApp()
Page({
data: {
list: [],
sumList: [],
array: [],
index: 0,
bzimg: "../../../icons/biaozhun.png",
popup: true,
patrolInfo: "",
hiddenmodalput: true,
finishid1A07DCE756E3430594233AA54C71144A: true,
major: "",
// imageList: [],
countIndex: 0,
arraylength: 0,
filep: "",
},
onLoad: function(options) {
var that = this;
var url = "";
if (options.type == "变电") {
url = app.data.baseurl + 'patrol/getTransPatrolList?major=' + options.type + '&devtype=' + options.type2
} else {
url = app.data.baseurl + 'patrol/getTransPatrolList?major=' + options.type
}
wx.request({
url: url,
success(res) {
if (options.type != "输电架空" && options.type != "输电通道") {
var newarr = new Array();
for (var obj in res.data) {
if (newarr.indexOf(res.data[obj].insidedevtype) == -1) {
newarr.push(res.data[obj].insidedevtype);
}
}
that.setData({
array: newarr,
arraylength: newarr.length
})
var objList = new Array();
for (var obj in res.data) {
if (res.data[obj].insidedevtype == newarr[0]) {
res.data[obj]["open"] = false
res.data[obj]["finish"] = false
res.data[obj]["imageList"] = []
objList.push(res.data[obj]);
}
}
that.setData({
list: objList,
sumList: res.data,
major: options.type
})
} else {
var objList = new Array();
for (var obj in res.data) {
res.data[obj]["open"] = false
res.data[obj]["finish"] = false
res.data[obj]["imageList"] = []
objList.push(res.data[obj]);
}
that.setData({
list: objList,
sumList: res.data,
major: options.type
})
}
}
})
},
onUnload: function () {//如果页面被卸载时被执行
},
bindPickerChange: function(e) {
var objList = new Array();
for (var obj in this.data.sumList) {
if (this.data.sumList[obj].insidedevtype == this.data.array[e.detail.value]) {
this.data.sumList[obj]["open"] = false
this.data.sumList[obj]["finish"] = false
this.data.sumList[obj]["imageList"] = []
objList.push(this.data.sumList[obj]);
}
}
this.setData({
list: objList,
major: this.data.major
})
this.setData({
index: e.detail.value
})
},
kindToggle: function(e) {
var id = e.currentTarget.id,
list = this.data.list;
for (var i = 0, len = list.length; i < len; ++i) {
if (list[i].id == id) {
list[i].open = !list[i].open
} else {
list[i].open = false
}
}
this.setData({
list: list
});
},
cancelM: function() {
this.setData({
hiddenmodalput: false
})
},
confirmM: function(e) {
this.setData({
hiddenmodalput: true
})
},
patrolFinish: function() {
wx.showModal({
title: '巡视完成',
content: '该站线或杆塔是否巡视完成?',
confirmText: "确定",
cancelText: "取消",
success: function(res) {
console.log(res);
if (res.confirm) {
console.log('用户点击主操作')
} else {
console.log('用户点击辅助操作')
}
}
});
},
/* 显示弹窗 */
criterionInfo(e) {
// this.hidePopup(false);
for (var obj in this.data.list) {
if (this.data.list[obj].id == e.currentTarget.dataset.id) {
var newCriterion = "";
var arr = this.data.list[obj].criterion.split(";");
for (var a in arr) {
newCriterion += arr[a] + " \n ";
}
this.setData({
hiddenmodalput: false,
patrolInfo: newCriterion
})
}
}
},
/**
* 图片选择
*/
chooseImage: function (e) {
var that = this;
wx.chooseImage({
count: 3,
sourceType: ['camera'],
//成功的回调
success: function (res) {
// var imageNewList = that.data.imageList;
// imageNewList.push(res.tempFilePaths);
// that.setData({
// imageList: imageNewList
// });
var objList = that.data.list;
for (var obj in that.data.list) {
if (that.data.list[obj].id == e.currentTarget.dataset.id) {
objList[obj].imageList.push(res.tempFilePaths);
}
}
that.setData({
list: objList
})
}
})
},
/**
* 上传
*/
uploadFile: function (e) {
var that = this;
var tag = 0;
for (var obj in that.data.list) {
if (that.data.list[obj].id == e.currentTarget.dataset.id) {
tag = obj;
}
}
//const index = e.target.dataset.index;
//向服务器端上传图片
if (that.data.list[tag].imageList != 0) {
for (var index in that.data.list[tag].imageList) {
var filePath = that.data.list[tag].imageList[index];
console.log("---------that.data.list[tag].imageList[index]------" + that.data.list[tag].imageList[index]);
wx.uploadFile({
url: app.data.baseurl + 'patrol/getPatrolImg',
// url : app.data.baseurl + 'baiduFaceAndCompare?sfzh=' + app.data.user.sfzh,
filePath: filePath + '',
name: 'file',
header: {
"Content-Type": "multipart/form-data"
},
// formData: {
// douploadpic: '1'
// },
success: function (res) {
console.log("成功进入后台");
var newlist = new Array();
var oldlist = that.data.list;
for (var obj in that.data.list){
if (that.data.list[obj].id == e.currentTarget.dataset.id){
oldlist[obj].finish = true;
}
}
that.setData({
list: oldlist
})
},
fail: function (err) {
console.log(err)
}
});
}
} else {
wx.showToast({
title: '未上传任何图片',
icon: 'loading',
duration: 1500
})
}
},
/**
* 预览
*/
previewImage: function (e) {
const index = e.target.dataset.index;
const current = e.target.dataset.src
var tag = 0;
for (var obj in this.data.list) {
if (this.data.list[obj].id == e.currentTarget.dataset.id) {
tag = obj;
}
}
wx.previewImage({
current: current,
urls: this.data.list[tag].imageList[index],
})
console.log('-----------------' + this.data.list[tag].imageList[index])
},
/**
* 删除
*/
deleteImage: function (e) {
var that = this;
var images = that.data.imageList;
var index = e.currentTarget.dataset.index; //获取当前长按图片下标
var tag = 0;
var newList = this.data.list
for (var obj in this.data.list) {
if (this.data.list[obj].id == e.currentTarget.dataset.id) {
tag = obj;
}
}
wx.showModal({
title: '提示',
content: '确定要删除此图片吗?',
success: function (res) {
if (res.confirm) {
console.log('点击确定了');
newList[tag].imageList.splice(index, 1);
} else if (res.cancel) {
console.log('点击取消了');
return false;
}
that.setData({
list:newList
});
}
})
}
});
WXSS:
.img_typeSetting_center {
display: flex;
justify-content: center;
align-items: center;
margin-top: 10%;
}
.btn_class {
margin-top: 10%;
width: 70%;
}
.titleTxt{
text-align: center;
color:white
}
page {
background-color: #5151A2;
}
.pogress_style {
margin-top: 10%;
margin-left: 15%;
align-items: center;
width: 70%;
}
.pogress_style_text {
z-index: 99999;
margin-top: 10%;
margin-left: 15%;
text-align: center;
width: 70%;
margin-top: -37px;
color: white;
}
JAVA后台 只贴关于上传部分的代码:
Controller
//获取当前日期时间的string类型用于文件名防重复
public String dates() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 巡视照片
*/
@RequestMapping(value = "getPatrolImg")
@ResponseBody
public void uploadPicture(HttpServletRequest request, HttpServletResponse response, PrintWriter writer,PatrolEntity entity) throws Exception {
System.out.println("进入get方法!");
//获取从前台传过来得图片
MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = req.getFile("file");
CommonsMultipartFile cFile = (CommonsMultipartFile) multipartFile;
DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
InputStream inputStream = fileItem.getInputStream();
// String base64 = imageToBase64Str(inputStream);
//获取图片的文件类型
String houzhu = multipartFile.getContentType();
int one = houzhu.lastIndexOf("/");
System.out.println(houzhu.substring((one + 1), houzhu.length()));
System.out.println(multipartFile.getName());
//根据获取到的文件类型截取出图片后缀
String type = houzhu.substring((one + 1), houzhu.length());
System.out.println(multipartFile.getContentType());
//获取到当前的日期时间用户生成文件名防止文件名重复
String filedata = this.dates();
//生成一个随机数来防止文件名重复
int x = (int) (Math.random() * 1000);
try {
File folder = new File("D://wxImg");
//判断文件夹是否存在
if (!folder.exists()) {
folder.mkdir();
}
String pathname = "D://wxImg//" + x + filedata + "." + type;
File file = new File(pathname);
//使用transferTo将file存起来
multipartFile.transferTo(file);
FileInputStream fileInputStream = new FileInputStream(file);
byte [] xml = FileCopyUtils.copyToByteArray(fileInputStream);
PatrolEntity pe = new PatrolEntity();
pe.setId("123");
pe.setMedia(xml);
service.uploadImg(pe);
System.out.println(fileInputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
mapper\mapper.xml\service都写到一个里面啦,自行进行区分哈!
/**
*mapper代码
*/
int uploadImg(PatrolEntity entity);
/**
* xml代码
*/
<insert id="uploadImg">
insert into T_ZZBD_PATROL_MEDIA (
ID
<if test="@Ognl@isNotEmpty(media)">
,MEDIA
</if>)
VALUES
(
#{id}
<if test="@Ognl@isNotEmpty(media)">
,#{media}
</if>)
</insert>
/**
* service代码
*/
public int uploadImg(PatrolEntity entity){
return mapper.uploadImg(entity);
}
数据库中效果:
刚接触开发不旧,基础比较差,还是个小萌新,希望大佬多多指正!
补充:index.js中的长按删除代码由于用户体验不好 改成了图片右上角的X