微信小程序批量上传封装 - Promise版

640 阅读1分钟

开篇:

发现公司上传没有封装,全是哪里用就在哪里 wx.upload(...), 于是简易的封装了。


直接上代码:

// 文件上传
function filesUpload(paths) {
    return new Promise((resolve, reject) => {
        wx.showLoading({
            title: '上传中, 请稍等..',
            mask: true
        })
        let uploadCount = 0; // 上传计数
        const resources = [] // 上传结果

        //上传图片
        for (const path of (typeof(paths) === 'string' ? [paths] : paths)) {
            wx.uploadFile({
                url: api.urlServer.ApiUrl + '/file/upload',
                filePath: path,
                name: 'file',
                timeout: 60 * 1000,
                success: function (res) {
                    let data = JSON.parse(res.data);
                    if (data.status == 0) {
                        resources.push(data.data.list)
                    }
                },
                complete: () => {
                    uploadCount++
                    if (uploadCount === paths.length || typeof(paths) === 'string') {
                        wx.hideLoading()
                        if (resources.length == 0) {
                            // showToast('上传失败')
                            reject('上传失败')
                        } else {
                            // showToast(paths instanceof String ? '上传成功' : '成功上传:' + resources.length + '张')
                            resolve(resources)
                        }
                    }
                }
            });
        }
    })
}

额外补充:

原本准备使用async 与 await 组合的,但是以往经验记着,需要单独引入 regeneratorRuntime 才能支持,则使用原始的方式, 写完后搜索了一下,发现开发工具《在 1.02.1904282 以及之后版本的开发工具中,增加了增强编译的选项来增强ES6转ES5的能力》, 故不需要单独引入即可使用了。 也懒得再重构了。

增强编译支持:


image.png

开启方式:


image.png