微信小程序一次上传多张照片

 data: {

    // 页面初始数据  

    imageList: [],

},

1、通过for 循环

  upLoadImage: function () {

    var that = this;

    wx.chooseMedia({

      count: 9,

      mediaType: ['image', 'video'],

      sourceType: ['album', 'camera'],

      maxDuration: 30,

      camera: 'back',

      success(res) {

        const tempFiles = res.tempFiles;

        // 初始化 imageList,如果之前为空的话  

        if (that.data.imageList.length === 0) {

          that.setData({

            imageList: tempFiles.map(file => ({

              ...file,

              serverId: null,

              serverUrl: null

            }))

          });

        }

       

        for (let i = 0; i < tempFiles.length; i++) {

          const file = tempFiles[i];

          wx.uploadFile({

            url: 'url', // 替换为您的服务器上传接口地址  

            filePath: file.tempFilePath,

            name: 'file', // 服务器通过这个字段接收文件  

            formData: {

              //'user': 'someone' // 额外表单信息,根据需要填写  

            },

            success: function (uploadRes) {

              // 文件上传成功后的回调  

              console.log('上传成功', uploadRes);

              try {

                // 解析服务器返回的JSON数据  

                const serverResponse = JSON.parse(uploadRes.data);

                // 从服务器响应中提取文件ID和URL  

                const fileID = serverResponse.data.fileID;

                const fileUrl = serverResponse.data.url;

                // 创建更新的文件对象  

                const updatedItem = {

                  ...file,

                  serverId: fileID,

                  serverUrl: fileUrl

                };

//这边获取了fileID 写入数据库了,不需要了,可以删除

                // 更新 imageList  

                const updatedImageList = that.data.imageList.map((item, index) => {

                  return index === i ? updatedItem : item;

                });

                // 更新界面显示  

                that.setData({

                  imageList: updatedImageList

                });

              } catch (error) {

                console.error('解析服务器响应失败', error);

              }

            },

            fail: function (uploadError) {

              // 文件上传失败后的回调  

              console.error('上传失败', uploadError);

            }

          });

        }

      },

      fail(err) {

        // 处理选择媒体失败的情况  

        console.error('选择媒体失败', err);

      }

    });

  },

2、通过forEach 循环

  upLoadImage1: function () {

    var that = this;

    wx.chooseMedia({

      count: 9,

      mediaType: ['image', 'video'],

      sourceType: ['album', 'camera'],

      maxDuration: 30,

      camera: 'back',

      success(res) {

        const tempFiles = res.tempFiles;

        // 初始化 imageList,如果之前为空的话  

        if (that.data.imageList.length === 0) {

          that.setData({

            imageList: tempFiles.map(file => ({

              ...file,

              serverId: null,

              serverUrl: null

            }))

          });

        }

        // 遍历临时文件数组,并上传每个文件  

        tempFiles.forEach(function (file, index) {

          wx.uploadFile({

            url: 'url', // 替换为您的服务器上传接口地址  

            filePath: file.tempFilePath,

            name: 'file', // 服务器通过这个字段接收文件  

            formData: {

              //'user': 'someone' // 额外表单信息,根据需要填写  

            },

            success: function (uploadRes) {

              // 文件上传成功后的回调  

              console.log('上传成功', uploadRes);

              try {

                // 解析服务器返回的JSON数据  

                const serverResponse = JSON.parse(uploadRes.data);

                // 从服务器响应中提取文件ID和URL  

                const fileID = serverResponse.data.fileID;

                const fileUrl = serverResponse.data.url;

                // 创建更新的文件对象  

                const updatedItem = {

                  ...file,

                  serverId: fileID,

                  serverUrl: fileUrl

                };

                // 更新 imageList,确保只有当前文件被更新  

                const updatedImageList = that.data.imageList.map(item => {

                  return item.tempFilePath === file.tempFilePath ? updatedItem : item;

                });

                // 更新界面显示  

                that.setData({

                  imageList: updatedImageList

                });

              } catch (error) {

                console.error('解析服务器响应失败', error);

              }

            },

            fail: function (uploadError) {

              // 文件上传失败后的回调  

              console.error('上传失败', uploadError);

            }

          });

        });

      },

      fail(err) {

        // 处理选择媒体失败的情况  

        console.error('选择媒体失败', err);

      }

    });

  },

  • 10
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
微信小程序中可以使用 `wx.uploadFile` 接口来实现一次接口批量上传图片和参数。首先,将所有需要上传的图片和参数存储到一个数组中。然后,遍历数组,使用 `wx.uploadFile` 分别上传每个图片和参数。最后,等待所有上传任务完成后,触发回调函数进行下一步操作。 以下是示例代码: ```javascript // 假设要上传的图片和参数都存储在以下两个数组中 const images = [file1, file2, file3]; const params = [{name: 'foo', value: 'bar'}, {name: 'baz', value: 'qux'}]; // 定义上传任务列表和上传完成计数器 const tasks = []; let count = 0; // 遍历图片数组,使用 wx.uploadFile 分别上传每个图片和参数 images.forEach((image, index) => { const task = wx.uploadFile({ url: '/upload', filePath: image, name: 'images', formData: params.reduce((formData, param) => { formData[param.name] = param.value; return formData; }, {}), success: res => { console.log(`image ${index} upload success!`); }, fail: err => { console.error(`image ${index} upload fail: ${err}`); }, complete: () => { count++; if (count === images.length) { console.log('all images upload complete!'); // 触发回调函数进行下一步操作 callback(); } } }); tasks.push(task); }); // 等待所有上传任务完成后,触发回调函数进行下一步操作 function callback() { // TODO: 下一步操作 } ``` 注意,以上代码仅为示例代码,实际应用中需要根据具体情况进行修改和调整。同时,由于小程序中上传任务数量限制,如果上传任务数量较多,可以考虑使用队列或其他技术进行优化。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值