小程序上传多张图片转base64

小程序上传多张图片转base64

在这里插入图片描述
XML代码:

<view style='background-color: #F1F1F1; width:100%rpx;height:3rpx;'></view>

    <view class='flex-item'>
      <text decode="{{true}}" style="font-size: 30rpx;">&emsp;实物照片</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
    })
  },
   })
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
微信小程序可以通过wx.request方法实现图片上传,而带参数的base64图片上传需要先将base64编码换为文件流并附加参数,然后再发送请求上传。以下是实现过程的示例代码: 1. 将base64编码换为文件流 ``` // 将base64编码换为文件流 function base64ToFile(base64Data, fileName) { const array = wx.base64ToArrayBuffer(base64Data) const filePath = `${wx.env.USER_DATA_PATH}/${fileName}` wx.getFileSystemManager().writeFile({ filePath, data: array, encoding: 'binary', success: () => { console.log('base64文件流成功') return filePath }, fail: () => { console.log('base64文件流失败') return null } }) } ``` 2. 将文件流和参数一起上传 ``` // 上传图片 function uploadImage(filePath, params) { const token = wx.getStorageSync('token') const header = { 'Authorization': `Bearer ${token}`, 'content-type': 'multipart/form-data' } wx.uploadFile({ url: 'https://example.com/upload', filePath: filePath, name: 'file', formData: params, header: header, success: (res) => { console.log('上传成功', res) }, fail: (res) => { console.log('上传失败', res) } }) } ``` 3. 调用函数进行上传 ``` const base64Data = 'data:image/png;base64,iVBORw0KGg...'; const fileName = 'image.png'; const params = {param1: 'value1', param2: 'value2'}; const filePath = base64ToFile(base64Data, fileName); uploadImage(filePath, params); ``` 注意:上传文件需要在开发者工具中设置“不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书”选项。在真机上测试时,需要在小程序管理后台的“开发设置”中添加上传图片的域名。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值