通过微信小程序实现文件上传效果
通过weui布局快速页面,将weui.wxss引入小程序,然后在app.wxss全局引入@import 'style/weui/weui.wxss';
文件上传会用到uploader,gallery以及输入输入框和按钮。
设计一个简单的页面
<form bindsubmit='doUpload'>
<view class="weui-cell weui-cell_active">
<view class="weui-cell__hd">
<view class="weui-label">标题</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" name="message" placeholder="请输入标题内容" />
</view>
</view>
<view class="weui-cell">
<view class="weui-cell__bd">
<view class="weui-uploader">
<view class="weui-uploader__hd">
<view class="weui-uploader__overview">
<view class="weui-uploader__title">图片上传</view>
<view class="weui-uploader__info">{{files.length}}/3</view>
</view>
<view class="weui-uploader__tips">
上传提示
</view>
</view>
<view class="weui-uploader__bd">
<view class="weui-uploader__files" id="uploaderFiles">
<block wx:for="{{files}}" wx:key="*this">
<view class="weui-uploader__file wrapper" bindtap="open" data-id="{{item}}" data-index="{{index}}"
bindlongpress="deleteImg">
<image class="weui-uploader__img" src="{{item}}" mode="aspectFill" />
</view>
<view wx:if="{{gallery}}" class="weui-gallery fadeIn" bindtap="close">
<view class="weui-gallery__info">{{imgIndex+1}}/{{uploadCount}}</view>
<view class="weui-gallery__img__wrp">
<image mode="aspectFit" class="weui-gallery__img" src="{{imgItem}}"></image>
</view>
<view class="weui-gallery__opr">
<view class="weui-gallery__del" data-index="{{imgIndex}}" data-id="{{imgItem}}" bindtap="deleteImg">
<i class="weui-icon-delete weui-icon_gallery-delete"></i>
</view>
</view>
</view>
</block>
</view>
<view class="weui-uploader__input-box">
<view class="weui-uploader__input" bindtap="chooseImage"></view>
</view>
</view>
</view>
</view>
</view>
<view class="page__bd">
<button class="weui-btn weui-btn_primary" form-type="submit">提交</button>
</view>
</form>
我对上传做了限制只允许上传三张,小程序规定最多只运行上传9张,如果不想用gallery可以用 wx.previewImage进行图片预览,小程序官方文档位置👇https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.previewImage.html
previewImage: function(e){
wx.previewImage({
current: e.currentTarget.id, // 当前显示图片的http链接
urls: this.data.files // 需要预览的图片http链接列表
})
}
上传api的调用说明👇,name是可以随便填的,于后台对应。(特别说明:图片只能一张一张的传,不然会报错)然后用递归还是用for循环都随你。
https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html
Page({
data: {
files: [],
uploadCount:3,
},
chooseImage: function (e) {
var that = this;
wx.chooseImage({
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
if (that.data.files.concat(res.tempFilePaths).length>3) {
wx.showToast({
title: '最多只能上传3张图片',
icon: 'none',
duration: 2000
})
return;
}
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
that.setData({
files: that.data.files.concat(res.tempFilePaths)
});
}
})
},
close: function() {
this.setData({
gallery: false,
});
},
open: function (e) {
console.log(e)
var imgItem = e.currentTarget.dataset.id;
var imgIndex = e.currentTarget.dataset.index;
this.setData({
gallery: true,
imgItem:imgItem,
imgIndex:imgIndex
});
},
deleteImg:function(e){
console.log(e)
var that = this;
var images = that.data.files;
var index = e.currentTarget.dataset.index;
wx.showModal({
cancelColor: 'cancelColor',
title:'系统提示',
content:'确定要删除该图片吗?',
success:function(res){
if(res.confirm){
images.splice(index,1);
}else if(res.cancel){
return false;
}
that.setData({
files:images
})
}
})
},
doUpload:function(e){
console.log(this.data.files)
var that = this;
var formObject = e.detail.value; //表单数据
var files = this.data.files;
var length =files.length;//总数
var successNum = 0; //成功
var failNum = 0; //失败
var count = 0; //当前第几张
that.uploadOneByOne(files,successNum,failNum,count,length,formObject);
},
uploadOneByOne:function(files,successNum,failNum,count,length,formObject){
var that = this;
wx.showLoading({
title: '正在上传第'+count+'张图片',
})
wx.uploadFile({
url:'http://127.0.0.1:80/wx/file/uploadHandler',
header:{
token:'QM_70ea580f1d5522333235a2017d93f028'
},
filePath:files[count],
name:'file',
formData:{
message:formObject.message
},
success:function(res){
successNum++;
console.log(res);
},
fail:function(res){
failNum++;//失败+1
console.log(res);
},
complete:function(res){
count++;//下一张
if(count == length){
//上传完毕,作一下提示
wx.showToast({
title: '成功上传' + successNum + ',' + '失败上传' + failNum,
icon: 'none',
duration: 2000
})
}else{
//递归调用,上传下一张
that.uploadOneByOne(files,successNum,failNum,count,length,formObject);
}
}
})
}
});
长按或者点击图片下方的删除按钮进行删除。
后台代码
@Slf4j
@RequestMapping("/wx/file")
@Api(value = "微信文件控制器", tags = {"微信文件操作接口"})
@RestController
public class WxFileController {
@RequestMapping(value="/uploadHandler")
@ApiOperation("上传测试")
public Map<String,Object> uploadHandler(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response){
String message = request.getParameter("message");
String fileName = file.getOriginalFilename();
String path = request.getSession().getServletContext().getRealPath("upload");
if (!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try{
file.transferTo(targetFile);
}catch (Exception e){
e.printStackTrace();
}
Map map = new HashMap();
map.put("code","1");
map.put("msg","处理成功");
return map;
}
}
有帮到你就扫一扫吧