vue3+腾讯云上传文件

1、引入腾讯云

npm i cos-js-sdk-v5 --save

2、调用后台接口获取上传需要的授权信息

// 获取上传授权信息
getUploadAuth() {
    let self = this;
    API.authInfo().then(res => {
        self.uploadSign = res.data;
    })
}

上传文件

<template>
    <el-upload :auto-upload="false" ref="upload">
        <el-button size="small" plain type="primary">选择文件</el-button>
    </el-upload>
</template>
// 点击上传文件
clickUpload() {
    let self = this;
    self.$refs.upload.submit(); // 取消自动上传功能,需调用el-uplaod的submit();
    self.$message.success('正在上传文件,请稍后');
    let cos = new COS({ // 创建一个COS实例
        getAuthorization(options, callback) {
            callback({
                TmpSecretId: self.uploadSign.Credentials.TmpSecretId, // 请求接口返回的数据
                TmpSecretKey: self.uploadSign.Credentials.TmpSecretKey, // 请求接口返回的数据
                SecurityToken: self.uploadSign.Credentials.Token, // 请求接口返回的数据
                ExpiredTime: self.uploadSign.ExpiredTime // 请求接口返回的数据
            });
        }
    });
    cos.putObject({
        Bucket: '', // 例如,examplebucket-1-1250000000
        Region: '', // 地区
        Key: fileName, // 上传的文件名
        StorageClass: 'STANDARD',
        Body: fileContent, // 上传文件对象
        }, function(err, data) {
            // err 上传失败
            // data 上传成功
            // data.Location 上传成功后的地址,如需在页面渲染需加入前缀'http://'或是'https://'
    })
}

评论

暂无评论