小程序上传多张图片转base64
XML代码:
<view style='background-color: #F1F1F1; width:100%rpx;height:3rpx;'></view>
<view class='flex-item'>
<text decode="{{true}}" style="font-size: 30rpx;"> 实物照片</text>
</view>
<view class='flex-item margin-top15rpx'style='width:800rpx;height:350rpx; margin-top:20px;'>
<view class="img">
<view class=" float-left" wx:for="{{imgs}}" wx:for-item="item" wx:key="*this">
<image src="{{item}}" data-index="{{index}}" mode="aspectFill" bindtap="previewImg" style='width:120rpx;height:150rpx;'></image>
<view class=" child2" data-index="{{index}}" catchtap="deleteImg">X</view>
</view>
<view class=" view float-left"style=" font-size: 120rpx;line-height: 120rpx;text-align: center;width:120rpx;color: #FFFBFC;" bindtap="chooseImg">+</view>
</view>
</view>
WXSS代码:
.float-left{
float: left;
}
.viewee{
position: fixed;
bottom: 0;
width: 100%;
}
.child2 {
width: 30rpx;
height: 30rpx;
border-radius: 50%;
background-color: red;
border: 3rpx solid red;
position: relative;
float: right;
margin-left: -13rpx;
margin-top: -18rpx;
font-size: 20rpx;
line-height: 30rpx;
text-align:center;
color: #FFFBFC;
}
JS代码:
var imgs; // 图片
var PhysicalPhoto=[]; //
var param = {};
var b = [];
Page({
data: {
imgs: [],
},
// 上传图片
chooseImg: function (e) {
var that = this;
imgs = this.data.imgs;
if (imgs.length >= 9) {
this.setData({
lenMore: 1
});
setTimeout(function () {
that.setData({
lenMore: 0
});
}, 2500);
return false;
}
wx.chooseImage({
// count: 1, // 默认9
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有 'original',
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
imgs = that.data.imgs;
for (var i = 0; i < tempFilePaths.length; i++) {
wx.getFileSystemManager().readFile({
filePath: res.tempFilePaths[i], //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => { //成功的回调
param = 'data:image/jpg;base64,' + res.data;
that.setData(param);
if (PhysicalPhoto != null) {
b = PhysicalPhoto;
}
b.push(param);
that.setData({
PhysicalPhoto: b
});
PhysicalPhoto = that.data.PhysicalPhoto;
console.log('64图:', PhysicalPhoto);
}
})
if (imgs.length >= 9) {
that.setData({
imgs: imgs
});
return false;
} else {
imgs.push(tempFilePaths[i]);
}
}
console.log("图片:",imgs);
that.setData({
imgs: imgs
});
}
});
},
// 删除图片
deleteImg: function (e) {
var that=this;
var imgs = that.data.imgs;
var index = e.currentTarget.dataset.index;
imgs.splice(index, 1);
var imtPhysicalPhoto = that.data.PhysicalPhoto;
var index = e.currentTarget.dataset.index;
imtPhysicalPhoto.splice(index, 1);
that.setData({
imgs: imgs,
PhysicalPhoto: imtPhysicalPhoto
});
},
// 预览图片
previewImg: function (e) {
//获取当前图片的下标
var index = e.currentTarget.dataset.index;
//所有图片
var imgs = this.data.imgs;
wx.previewImage({
//当前显示图片
current: imgs[index],
//所有图片
urls: imgs
})
},
})