小程序封装图片上传阿里云OSS
app.js中 写入
wxPromisify(fn) { return function (obj = {}) { return new Promise((resolve, reject) => { obj.success = function (res) { resolve(res) } obj.fail = function (res) { reject(res) } fn(obj)//执行函数,obj为传入函数的参数 }) } }
在utils文件夹下新建uploadOssUtil.js文件
let app = getApp(); var uploadFile = app.wxPromisify(wx.uploadFile) let signObj = null; // 上传文件到阿里云OSS function uploadFileToOSS(fileList) { return new Promise(function(resolve, reject) { let startTime = new Date().getTime() // 开始执行上传 var promise = Promise.all(fileList.map((item, index) => { console.log(item) return new Promise(function(resolve, reject) { console.log("刷新上传凭证") wx.request({ url:"*********", //调用接口,让后端返回上传所需要的字段 methods: "get", data:"", success:res=>{ if (res.data.code == '20000') { signObj = res.data.data; var aliyunFileKey; console.log("上传参数" + JSON.stringify(item)); aliyunFieKey=signObj.dir + new Date().getTime() + '_' + item.size + "." + item.type; console.log(aliyunFileKey); // console.log("上传参数" + JSON.stringify(item)) uploadFile({ url: signObj.host, //上传到OSS filePath: item.path, name: 'file', formData: { 'key': aliyunFileKey, 'OSSAccessKeyId': signObj.accessid, 'policy': signObj.policy, 'signature': signObj.signature, 'success_action_status': '200' } }).then(res => { item.url = signObj.host + aliyunFileKey; console.log(item.url) resolve(item) }) } else { reject("获取上传凭证失败") } } }) }) })).then(res => { let endTime = new Date().getTime() console.log("上传文件完毕,共耗时:" + (endTime - startTime) + "ms") resolve(res) }) }) }
最后把文件导出
module.exports = { uploadFileToOSS: uploadFileToOSS };