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