选择图片wxml中用的是ColorUI的组件,挺好用:
<view class="cu-bar bg-white margin-top">
<view class="action">
图片上传
</view>
<view class="action">
{{imgList.length}}/4
</view>
</view>
<view class="cu-form-group">
<view class="grid col-4 grid-square flex-sub">
<view class="bg-img" wx:for="{{imgList}}" wx:key="{{index}}" bindtap="ViewImage" data-url="{{imgList[index]}}">
<image src='{{imgList[index]}}' mode='aspectFill'></image>
<view class="cu-tag bg-red" catchtap="DelImg" data-index="{{index}}">
<text class="cuIcon-close"></text>
</view>
</view>
<view class="solids" bindtap="ChooseImage" wx:if="{{imgList.length<4}}">
<text class="cuIcon-cameraadd"></text>
</view>
</view>
</view>
<button class="cu-btn block bg-blue margin-tb-sm lg" formType="submit" bindtap="publish_bbs" data-target="Modal">发布</button>
js:
ViewImage(e) {
wx.previewImage({
urls: this.data.imgList,
current: e.currentTarget.dataset.url
});
},
//选择图片
ChooseImage() {
wx.chooseImage({
count: 4, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: (res) => {
if (this.data.imgList.length != 0) {
this.setData({
imgList: this.data.imgList.concat(res.tempFilePaths)
})
} else {
this.setData({
imgList: res.tempFilePaths
})
}
}
});
},
//删除图片
DelImg(e) {
this.data.imgList.splice(e.currentTarget.dataset.index, 1);
this.setData({
imgList: this.data.imgList
})
},
formSubmit: function (e) {
for (var i = 0; i < that.data.imgList.length; i++) {
wx.uploadFile({
url: app.globalData.url + '/appInterface/fileUpload.do',
filePath: that.data.imgList[i],
name: 'files',
success: function (ares) {
that.data.imgpathlist.push(JSON.parse(ares.data).msg)
if (i == that.data.imgList.length){
that.setData({
run: true
})
}
}
})
}
},
后台代码:
@RequestMapping("/fileUpload")
@ResponseBody
public static Json uploadFilesForWEditor(MultipartFile files,HttpServletRequest request,HttpServletResponse response){
Json j = new Json();
j.setSuccess(false);
try{
String result=FileUploadUtils.fileUpload(files, request, response);
if(result != null){
j.setMsg(result);
j.setSuccess(true);
}
}catch(Exception e){
e.printStackTrace();
j.setMsg("图片上传异常" + e.getMessage());
j.setSuccess(false);
}
return j;
}
调用方法代码:
public static String fileUpload(MultipartFile file,HttpServletRequest request,HttpServletResponse response){
Json json = new Json();
String fileName = "";
json.setSuccess(true);
fileName = file.getOriginalFilename();
String rootPath = request.getServletContext().getRealPath("/")+"upload/";
fileName=PbUtils.getUUID()+fileName.substring(fileName.lastIndexOf("."));
String path = rootPath + fileName;
File parentPath=new File(path);
if(!parentPath.exists()){
parentPath.mkdirs();
}
try {
file.transferTo(new File(path));
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "/upload/"+fileName;
}