阿里云oss上传(图片、分片)

946 阅读2分钟

前期准备

sdk地址:传送门

1.安装

npm install ali-oss  

2.引入并实例化OSS

import OSS from "ali-oss";

this.client = new OSS({
    // yourRegion填写Bucket所在地域。以华东1(杭州)为例,Region填写为oss-cn-hangzhou
    region: yourRegion,
    bucket: yourBucketName,
    // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
    accessKeyId: yourAccessKeyId,
    accessKeySecret: yourAccessKeySecret,
    expiration:yourExpiration,
    // 从STS服务获取的安全令牌(SecurityToken)。
    stsToken: yourSecurityToken,
});

图片上传

/**
 *  oss上传图片时转化为buffer
 * @param {bold} img 图片流 
 */
readFileAsBuffer(file) {
    const reader = new FileReader();
    return new Promise((resolve) => {
        reader.readAsDataURL(file);
        reader.onload = function () {
            const base64File = reader.result.replace(
                /^data:\w+\/\w+;base64,/,
                ""
            );
            resolve(new OSS.Buffer(base64File, "base64"));
        };
    });
}
// 图片上传到oss
upload(file) {
    new Promise((resolve) => {
    // 此处要使用oss生成对应的buffer
        let buf = this.readFileAsBuffer(file);
        resolve(buf);
    }).then((buf) => {
        // 此处文件名若有重复的,会在阿里云oss上生成不同版本的文件,配置服务器上的oss可以在上传的时候获取到对应的版本,
        // 后续通过版本和路径可以拿到对应的内容,此处不详细介绍了
                    let url = 'img/userId/1' // 此处的'/'会上传到阿里云对应的目录文件夹下,没有文件夹,会自动新建
        this.client.put(url, buf).then((res) => {
            console.log(res);
            this.signatureUrl(res)
            })
       })
}
// 生成能够回显的地址(3600秒的有效时间)
signatureUrl(data){
// 此时的url就是可以访问链接
    let url = this.client.signatureUrl(decodeURIComponent(data.name), {
        expires: 3600,
    });
}

分片上传

// 分片上传
upload(file) {
    new Promise((resolve, reject) => {
        try {
            let url = 'img/userId/1' 
            this.client.multipartUpload(url, file, {
                    // 获取上传进度
                    progress: function (p, cpt, res) {
                        let precent = `${Math.floor(p * 100)}%`;
                     }
                 }).then((res) => {
                    console.log(res);
                    this.signatureUrl(res)
                    })
             catch (e) {
                console.log(e);
                alert("上传失败,请重新上传")
            }
      })
}
其他说明

有涉及到上传相关的版本,图片处理相关的问题,也可以交流哦
针对oss使用的问题,可以先查看oss的sdk文档传送门,不能解决的可以加入钉钉群(此处不在放),群里有对应的人回答,特殊的问题需要工单咨询。(别忘记服务器上的配置哦)