「OSS」阿里云OSS 浏览器直传

阿里云OSS 浏览器直传

官方文档

首先是签名 也是阿里推荐的 STS模式-即临时身份令牌

由服务器签发一次,然后客户端用此实例化OSS对象进行上传。

// 获取STS签名
get_STS() {
  return new Promise(async (resolve, reject) => {
    let name = new Date().getTime() + Math.random();
    let operate = "uploadImg";
    let that = this;
    // 请求后端接口获取STS签名,此处为后端需要的参数,基本都是自定义的 也可不传。
    let res = await get_STS({
      name,
      operate,
      sign: crypto.MD5(name + operate + "bayinabayin888").toString()
    });
    if (res.data.code != 200) {
      that.$alert(res.data.message || res.data.msg);
    } else {
      resolve(res.data.data);
    }
  });
}
// 上传单图

let OSS = require('ali-oss');
// img_blob为选择的文件对象
async upload_img_to_oss(img_blob) {
  return new Promise(async (resolve, reject) => {
    let oss_sign = await this.get_STS();
    let client = new OSS({
      accessKeyId: oss_sign.AccessKeyId,
      accessKeySecret: oss_sign.AccessKeySecret,
      stsToken: oss_sign.SecurityToken,
      endpoint: "oss-cn-beijing.aliyuncs.com/",
      bucket: "xxx-test"
    });

    let result = await client.put(
      "xxx/" + oss_sign.AccessKeyId,
      img_blob
    );

    // console.log(result);
    resolve(result);
  });
}

发表评论

电子邮件地址不会被公开。