Electron-Vue 使用 oss 實現上傳、下載


一、安裝阿里雲 OSS

npm install ali-oss

二、使用 require 進行引用

let OSS = require('ali-oss');

三、上傳文件

async doUpload(){
  const _this = this;
  let client = new OSS({
    region:_this.region,
    accessKeyId: _this.keyId,
    accessKeySecret: _this.keySecret,
    bucket:_this.bucket
  });

  try {
    let result = await client.put('srv2.0-nl/test1.jpg', 'C:\\Users\\Administrator\\Desktop\\光速4.jpg')
    console.log('上傳成功');
    console.log(result);
  } catch(e) {
    console.log('出錯了');
    console.log(e);
  }
}

四、分片上傳

const progress = async function(p) {
  //  進度百分比(0-1之間小數)
  console.log(p);
}
async multipartUpload() {
  const _this = this;
  let client = new OSS({
    region:_this.region,
    accessKeyId: _this.keyId,
    accessKeySecret: _this.keySecret,
    bucket:_this.bucket
  });

  try {
    let result = await client.multipartUpload('srv2.0-nl/test1.jpg', 'C:\\Users\\Administrator\\Desktop\\光速3.jpg', {
      progress,
      meta: {
        year: 2017,
        people: 'test'
      }
    });
    console.log(result);
    let head = await client.head('srv2.0-nl/test1.jpg');
    console.log(head);
  } catch (e) {
    // 捕獲超時異常
    if (e.code === 'ConnectionTimeoutError') {
      console.log("Woops,超時啦!");
      // do ConnectionTimeoutError operation
    }
    console.log(e)
  }
}

說明:

meta 參數是一個用戶自定義的元數據,通過 head 接口可以獲取到 object 的 meta 數據。

progress 參數是一個進度回調函數,用於獲取上傳進度。progress可以是一個 async 函數。

五、下載文件

async download() {
  const _this = this;
  let client = new OSS({
    region:_this.region,
    accessKeyId: _this.keyId,
    accessKeySecret: _this.keySecret,
    bucket:_this.bucket
  });

  try {
    let result = await client.get('srv2.0-nl/test1.jpg', 'C:\\Users\\Administrator\\Desktop\\下載.jpg');
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM