收藏
回答

wx.uploadFile()如何封装promise?

问题模块 框架类型 问题类型 API/组件名称 终端类型 微信版本 基础库版本
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)
        })
    })
}



最后一次编辑于  2018-09-19  (未经腾讯允许,不得转载)
邀请回答
复制链接收藏关注问题回答

2 个回答

  • 卢霄霄
    卢霄霄
    2018-09-19

    const uploadImg = (filePath,progressCallback) => {

        uploadTask.onProgressUpdate(res=>{

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

        })

    })


    const progressUpdate = function(e){}

    2018-09-19
    赞同
    回复
  • 王琦
    王琦
    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
    赞同
    回复