//app.js
uploadimg(data) {
var that = this,
i = data.i ? data.i : 0, //当前上传的哪张图片
success = data.success ? data.success : 0, //上传成功的个数
fail = data.fail ? data.fail : 0; //上传失败的个数
wx.uploadFile({
url: data.url,
filePath: data.path[i],
name: 'file', //这里根据自己的实际情况改
formData: null, //这里是上传图片时一起上传的数据
success: (resp) => {
success++; //图片上传成功,图片上传成功的变量+1
console.log(resp)
console.log(i);
//这里可能有BUG,失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时,这里的success才+1
},
fail: (res) => {
fail++; //图片上传失败,图片上传失败的变量+1
// console.log('fail:' + i + "fail:" + fail);
console.log('fail:', res);
},
complete: () => {
console.log(i);
i++; //这个图片执行完上传后,开始上传下一张
if (i == data.path.length) { //当图片传完时,停止调用
console.log('执行完毕');
console.log('成功:' + success + " 失败:" + fail);
} else { //若图片还没有传完,则继续调用函数
console.log(i);
data.i = i;
data.success = success;
data.fail = fail;
that.uploadimg(data);
}
}
})
},
wxml
<!-- 选择图片 -->
<view class='up-pic'>
<view class='flex pic-box'>
<block wx:key="imgbox" wx:for="{{pics}}">
<view class='ap-box'>
<view class='add-pic'>
<image class='add-pic' src='{{item}}'></image>
<view class='img-de' data-deindex='{{index}}' bindtap='imgDelete1'>X
<!-- //右上角的删除按钮图片 -->
</view>
</view>
</view>
</block>
<view bindtap="upimg" bindtap='choose' wx:if="{{pics.length<9}}" class="up">+</view>
<view bindtap="uploadimg" wx:if="{{pics.length>=1}}" class="up">上传</view>
</view>
</view>
css
.up{
margin:30rpx;
height: 200rpx;
background: #ccc;
color: #fff;
font-size: 100rpx;
text-align: center;
line-height: 200rpx
}
/* 上传图片 */
.flex{
display: flex;
}
.up-pic{
/* padding:20rpx 24rpx; */
width: 100%;
justify-content: center;
}
.pic-box{
margin-top:20rpx;
flex-flow:wrap;
width:95%;
}
.ap-box{
position: relative;
}
.add-pic{
width: 160rpx;
height: 160rpx;
margin-right: 20rpx;
position: relative;
margin: 20rpx 30rpx 20rpx 30rpx;
}
/* 删除图片 */
.img-de{
width:45rpx;
height:45rpx;
border-radius:50%;
position:absolute;
right:-41rpx;
top:5rpx;
}
.hong-contant .teamwork-btn{
width: 360rpx;
height: 88rpx;
border-radius: 50rpx;
color: white;
background-color:#14a1fd;
margin: 0 auto;
margin-top: 80rpx;
margin-bottom: 40rpx;
}
js
var app = getApp();
Page({
data: {
pics: []
},
choose: function () {//这里是选取图片的方法
var that = this,
pics = this.data.pics;
wx.chooseImage({
count: 9 - pics.length, // 最多可以选择的图片张数,默认9
sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
success: function (res) {
var imgsrc = res.tempFilePaths;
pics = pics.concat(imgsrc);
that.setData({
pics: pics
});
},
fail: function () {
// fail
},
complete: function () {
// complete
}
})
},
uploadimg: function () {//这里触发图片上传的方法
var pics = this.data.pics;
app.uploadimg({
url: 'https://........',//这里是你图片上传的接口
path: pics//这里是选取的图片的地址数组
});
},
onLoad: function (options) {
}
})