小程序和uniapp实现多图上传功能

一、官方实现图片上传示例:

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
      }
    })
  }
})

二、这里对功能进行拆分,具体如下:

1.定义上传功能函数

/**
 * 对小程序图片上传功能进行封装(需更灵活操作,可对代码进行优化)
 */
const uploadFile = (_data, _path) => {
    return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
          filePath: _path,
          name: 'file',
          formData: _data,
          success (res){
            resolve(res.data);
          },
          fail (msg){
            reject();
          }
        })
    });
}

2.选择图片并上传所有图片,通过Promise.all实现多图同步上传功能

wx.chooseImage({
  success (res) {
    //此处可添加wx.showLoading提示上传信息
    //实现多图上传
    Promise.all(
        /*
        通过map、Promise功能实现同时上传多张图片功能
        此处map返回结果为 [uploadFile({}, '图片路径'), uploadFile({}, '图片路径'), ...]
        */
        res.tempFilePaths.map( item => uploadFile({}, item) )
    ).then(res => {
        /*
        如Promise执行前添加wx.showLoading函数
        执行完毕后此处必须执行wx.hideLoading函数
        */

        //输入所有上传成功图片的结果集
        console.log(res);
        //通过返回res数据进行相应处理
    }).catch(msg => {
        /*
        如Promise执行前添加wx.showLoading函数
        执行完毕后此处必须执行wx.hideLoading函数
        */
        console.error(msg);
    });
   
  }
})

三、Uniapp实现

同小程序实现方式一样,由于两者函数定义基本一致,这里涉及到的函数调用,所有wx修改成uni即可。

你可能感兴趣的:(小程序,微信小程序,小程序,javascript)