小程序 阿里云oss私有Bucket內部Object的上傳及下載

前言:目前阿里云公有Bucket的上傳網上已有很多,下載只需直接訪問連接。本文介紹私有Bucket的上傳及下載。

1.上傳

小程序要上傳文件必須使用微信的 wx.uploadFile方法

因此需要配置阿里云參數

key:你想要的文件名

policy:用戶表單上傳的策略(Policy),是經過base64編碼過的字符串。

accessid:用戶請求的accessid。

signature:對變量policy簽名后的字符串。

expire:上傳策略失效時間,在PolicyText里指定。在失效時間之前,都可以利用此Policy上傳文件,所以沒有必要每次上傳都去服務端獲取簽名。

在util.js編寫通用請求方法


function uploadimag(path) {

  return new Promise((resove, reject) => {

    wx.request({

      method: 'GET',

      url: baseurl + '/user/aliyunSTS/getAliyunSignature',//請求服務器獲取oss配置

      data: '',

      header: {

        'content-type': 'application/json',

        'jwt': wx.getStorageSync('jwt'),//我們使用jwt鑒權

      },

      success(res) {

        if (parseInt(res.data.status) == 0) {

          var key = res.data.retValue.dir + 'patient/' + new Date().getTime() + Math.floor(Math.random() * 999) + '.png';

          wx.uploadFile({

            url: 'https://' + point + '.oss-cn-hangzhou.aliyuncs.com', //開發者服務器 url

            filePath: path, //要上傳文件資源的路徑

            name: 'file', //必須填file

            formData: {

              'key': key,

              'policy': res.data.retValue.policy,

              'OSSAccessKeyId': res.data.retValue.accessid,

              'signature': res.data.retValue.signature,

              'success_action_status': '200',

            },

            success: function(re) {

              if (re.statusCode != 200) {

                reject('上傳失敗');

                console.log('上傳失敗');

              } else

                resove(key);

              console.log('上傳成功');

            },

            fail: function(err) {

              reject('失敗');

              console.log('失敗');

            },

          })

        }

      }

    })

  })

}


util.uploadimag(img1).then(path =>console.log(path)//path為上傳的圖片名

).catch(console.log('上傳成功'));

2.下載

服務器端配置:https://help.aliyun.com/document_detail/31857.html?spm=a2c4g.11186623.6.617.5e07715fJbCAum

由于小程序無法使用oss的sdk,可以配置第三方授權訪問的url


function getimg(path) {

  return new Promise((resove, reject) => {

    wx.request({

      method: 'GET',

      url: baseurl + '/user/aliyunSTS/getAliyunGeneratePresignedUrl',//服務器配置獲取接口

      data: {

        'path': path

      },

      header: {

        'content-type': 'application/json',

        'jwt': wx.getStorageSync('jwt'),

      },

      success(res) {

        if (parseInt(res.data.status) == 0) {

          resove(res.data.retValue);

        }

      },

      fail: function(err) {

        reject('失敗');

      }

    })

  })

}

在其他地方直接調用


 // 獲取圖片路徑,存入字典

  makeimg: function (oldpath) {

    var that = this;

    var dic = that.data.imgdic;

    util.getimg(oldpath).then(newpath => {

      dic[oldpath] = newpath;//返回的圖片鏈接,可直接訪問

      that.setData({

        imgdic: dic

      })

    }).catch(console.log('請求完成'));

  },

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容