收藏
回答

wx.uploadFile()如何封装promise?

框架类型 问题类型 API/组件名称 终端类型 微信版本 基础库版本
小程序 需求 wx.uploadFile 客户端 6.7.2 2.2.3

wx.uploadFile()不支持多图片上传,


只能用递归。


打算封装成promise


但是我既想resolve出success中的结果,又想监听到uploadTask的上传进度


我该怎么办呢?


resolve 不知道放在哪?


// 上传图片
const uploadImg = (filePath) => {
    return new Promise((resolve, reject) => {
        const uploadTask = wx.uploadFile({
            url: app.globalData.baseUrl + '/wechat/app/common/uploadImage',
            filePath: filePath,
            name: 'file',
            formData: {
                'path': 'm0'
            },
            success: function (res) {
                console.log(res, 888)
                let d = JSON.parse(res.data)
                console.log(d)

                if (res.statusCode == 200 && d.code == 1) {

                  // resolve(res)

                    console.log(d.data)
                } else {
                    wx.showToast({
                        title: '当前网络不佳,请稍后重试',
                        icon: 'none'
                    })
                }
            },
            fail(err) {
                wx.showToast({
                    title: '当前网络不佳,请稍后重试',
                    icon: 'none'
                })
            }
        })
 
        uploadTask.onProgressUpdate((res) => {
            // resolve(res)
            console.log(res)
        })
    })
}



回答关注问题邀请回答
收藏

2 个回答

  • 王琦
    王琦
    2018-09-19


    let app = getApp();
    module.exports = function (url, filePath) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: `${app.globalData.apiUrl}sys/${url}`,
                filePath,
                name: 'file',
                formData: {
                    'user': 'test'
                },
                method: 'POST',
                header: {
                    'Authorization': `Bearer${app.globalData.userToken}`
                },
                success: resolve,
                fail: reject
            })
        })
    }


    const uploadFile = require('../../utils/uploadFile.js');


    let files = this.data.files;


    let uploads = [];
    files.forEach(ele => {
      uploads.push(uploadFile('upload', ele))

    })


    Promise.all(uploads).then(res=>{
    //todo
    })


    2018-09-19
    有用 4
    回复 1
    • 凛冬的寒风
      凛冬的寒风
      2021-10-28
      感谢封装,上手能用
      2021-10-28
      1
      回复
  • 卢霄霄
    卢霄霄
    2018-09-19

    const uploadImg = (filePath,progressCallback) => {

        uploadTask.onProgressUpdate(res=>{

            typeof(progressCallback) == 'function' && progressCallback(res)

        })

    })


    const progressUpdate = function(e){}

    2018-09-19
    有用
    回复
登录 后发表内容