• 小程序封装图片上传阿里云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
    
    };
    

      

  • 相关阅读:
    IOS 给一个文本框,按钮,view加虚线边框
    AFNetworking 使用  基础篇
    IOS——中级篇 --TableView以及Cell
    IOS中级篇 —— picKerView and DatePicKer
    IOS中级篇 ——自动布局 Autolayout  and  VFL
    IOS中级篇—— 多线程--NSOperation
    IOS中级篇 —— Autoresizing
    IOS中级篇 —— 字典转模型
    IOS中级篇 —— 关于深复制和浅复制
    IOS中级篇 —— 日期时间对象
  • 原文地址:https://www.cnblogs.com/BySee1423/p/12613578.html
Copyright © 2020-2023  润新知