html:
<view wx:for="{{imgList}}">
<image src="{{item}}" class="uploadImg"></image>
<image class='delete' src="../../imgs/close.png" bindtap='clearImg' data-index="{{index}}"></image>
</view>
js页面:
data: {
imgList: [] //页面显示的图片列表
},
//上传图片,如果不设置count默认最多传9张
joinPicture: function(e) {
var that = this
//设置最多上传的图片数量
if (that.data.imgList.length >= 9) {
wx.showModal({
title: '',
content: '最多上传9张图片',
showCancel: false,
})
return;
}
//选择图片
wx.chooseImage({
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
// that.data.evalList.push.apply(that.data.evalList, res.tempFilePaths); //数组合并
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths; //that.data.evalList//
//启动上传等待中... 上传提示框
wx.showToast({
title: '正在上传...',
icon: 'loading',
mask: true,
duration: 10000
})
// console.log(that.data.evalList)
var uploadImgCount = 0;
// console.log(tempFilePaths)
//遍历每个图片 去执行uploadFile
for (var i = 0, h = tempFilePaths.length; i < h; i++) {
// console.log(tempFilePaths[i])
wx.uploadFile({
url: app.globalData.imgUrl,//接受文件的url
filePath: tempFilePaths[i],//字符串
name: 'images',//后台接受的字段名称
header: {
'token': wx.getStorageSync('token')
},
success: function(res) {
uploadImgCount++;
var data = JSON.parse(res.data);
// console.log(data)
that.data.imgList.push(data.replace(/[\\]/g, '').replace(/\"/g, "")) //得到的数据添加到imgList中
that.setData({
imgList: that.data.imgList
})
//如果是最后一张,则隐藏等待中
if (uploadImgCount == tempFilePaths.length) {
wx.hideToast();
}
},
fail: function(res) {
console.log(res)
wx.hideToast();
wx.showModal({
title: '错误提示',
content: '上传图片失败',
showCancel: false,
success: function(res) {}
})
}
});
}
}
});
//
},
//删除图片
clearImg: function (e) {
var index = e.currentTarget.dataset.index;//获取当前图片的索引
var imgList = this.data.imgList;
imgList.splice(index, 1);//从当前的图片列表中去除这一项
this.setData({
imgList: imgList//重新赋值
})
},
单张图片上传代码:
wx.chooseImage({
success (res) {
const tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],//注意不要加引号
name: 'file',
formData: {//其他需要传的数据
'user': 'test'
},
success (res){
const data = res.data
//do something
}
})
}
})
写这块的时候真是遇见两个坑:
- filePath: tempFilePaths[i],//注意这里必须是String!!!
-
filePath 如果传的是单张,不要带上双引号
欢迎大家赞赏