图片上传
- wx.chooseMedia() 选择图片,保存到返回临时路径
- wx.uploadFile() 上传到服务器
upload.wxml
<view bindtap='chooseSheet'>上传</view>
upload.js
chooseSheet: function() { let that = this; wx.showActionSheet({ itemList: [ "从相册中选择", "拍照" ], itemColor: "#f7982a", success: function(e) { e.cancel || (0 == e.tapIndex ? that.chooseImg("album") : 1 == e.tapIndex && that.chooseImg("camera")); } }); }, //type:选择的类型 //album:相册 //camera拍照 chooseImg: function(type) { var that = this; wx.chooseMedia({ mediaType: 'image', sourceType: type, count:1, success: function(a) { if(a.tempFiles[0].size> 2097152){ wx.showModal({ content: "选择的图片过大,请上传不超过2M的图片", showCancel: !1 }) }else{ //把图片上传到服务器 that.upload(a.tempFiles[0]) } } }); }, uploadImg: function(tempFiles){ wx.showLoading({ title: "上传中" }); wx.uploadFile({ url:url, filePath: e,//图片路径 name: tempFiles.tempFilePath, formData: { token: a.globalData.token, file: "filePath" }, header: { "Content-Type": "multipart/form-data" }, success: function(a) { wx.hideLoading(); wx.showToast({ title: "上传成功", icon: "success", duration: 3000 }); }, fail: function(a) { wx.hideLoading(); wx.showToast({ title: "上传失败", icon: "none", duration: 3000 }); } }); }
批量多张图片如何上传?
解决思路是定义一个递归函数,递归调用
wx.uploadFile
上传,全部完成后结束递归。
upload.js
data: {
//上传图片列表
imgs:[],
//已上传成功的图片路径
imgPath:[],
},
method: {
// 上传照片
chooseImg (e) {
const that = this;
let imgs = this.data.imgs || [];
let imgNumber = imgs .length;
//还能上传的剩余个数
if(imgNumber >= 3){
wx.showToast({ title: "超出上传个数"});
return false;
}else{
imgNumber = 3 - imgNumber;
};
//打开本地相册选择图片
wx.chooseMedia({
count: imgNumber,
mediaType: 'image',
sourceType: ['album', 'camera'],
success (res) {
const tempFiles= res.tempFiles;
for(let i = 0;i < tempFiles.length; i++){
imgs.push(tempFiles[i]);
}
//赋值,回显照片
that .setData({
imgs: imgs
});
let successUp = 0; //成功
let failUp = 0; //失败
let count = 0; //第几张
let length = tempFiles.length; //总数
//调用上传方法
that.btachUpload(tempFilePaths, successUp, failUp, count, length);
}
})
},
btachUpload:function(imgPaths, successUp, failUp, count, length){
var that= this;
wx.showLoading({title: '正在上传第' + count + '张', });
wx.uploadFile({
url: url,
filePath: imgPaths[count].tempFilePath,
formData:{
userId:app.globalData.userMsg.userId
},
name: "uploadImage",
header: {
'content-type': 'multipart/form-data'
},
success (e) {
let path = that.data.imgPath;
let obj = e.data;
if(obj.code == 200){
path.push(obj.infoObject);
that.setData({
imgPath:path
});
}
successUp++;//成功+1
},
fail (e) {
failUp++; //失败+1
},
complete (e) {
//下一张
count++;
if(count == length){
FN.Toast(`上传成功${successUp}`)
}else{
//递归调用,上传下一张
that.btachUpload(imgPaths, successUp, failUp, count, length);
}
}
})
}
}