阿里云 OSS 签名上传(结合 elementUI)

原理:从服务端获取签名,js直接上传阿里云OSS服务器。

文档:

elementui主要代码

template:

<el-form-item label="上传图片" prop="video">
    <el-upload id="video"  action
        :data="aliyunOssToken"
        :http-request="uploadVideo"
        :headers="header">
        <img v-if="form.cover" :src="form.cover">
        <el-button class="avatar-uploader-icon" type="primary">上传</el-button>
    </el-upload>
</el-form-item>

script:

upload(file){
    var _self = this;
    let imgType = file.file.type.split("/")[1].toLowerCase();
    if (imgType != 'jpg' && imgType != 'png') {
        this.$message.error('请上传图片类型');
        return;
    }
    getOSSToken().then(function(res){
        _self.aliyunOssToken = res.data;
        var ossData = {};
        //key就代表文件层级和阿里云上的文件名
        let imgType = file.file.type.split("/")[1];
        let filename = file.file.name + file.file.size; //md5对图片名称进行加密
        let keyValue = "images/" + md5(new Date() + filename) + "." + imgType;

        // 组装formdata
        let formdata = new FormData();
        formdata.append('name', file.file.name)
        formdata.append('key', keyValue)
        formdata.append('policy', _self.aliyunOssToken.policy)
        formdata.append('OSSAccessKeyId', _self.aliyunOssToken.accessid)
        formdata.append('success_action_status', 200)
        formdata.append('signature', _self.aliyunOssToken.signature)
        formdata.append('file', file.file)

        _self.uploadOSS(formdata, _self.aliyunOssToken.host).then(function(res){
            _self.form.cover = _self.aliyunOssToken.host + '/' + keyValue;
            _self.$message.success('上传成功');
        }).catch(function(error){
            _self.$message.error('上传失败');
            console.log(error);
        })
    }).catch(function(error){
        console.log(error);
    })
},
uploadOSS(formData, url) {
  const config = {
    headers: { "Content-Type": "multipart/form-data;boundary="+new Date().getTime() }
    };
  return axios.post(url,formData,config);
}

其中:务必使用表单提交方式,aliyunOssToken格式如下

{
    "accessid": "LToofXWKudxfoAlI",
    "host": "https:\/\/xxx.oss-cn-hangzhou.aliyuncs.com",
    "policy": "eyJleHBpgfdgdf676uIjoiQxODowNzowMFoiLCJjb25kaXRpb25zIjpbWyJjb250ZW50LWxlbmd0aC17ewreMDQ4NTc2MDAwXSxbInN0YXJ0cy13aXRoIiwiJGtleSIsInZpZGVvXC8iXV19",
    "signature": "H46g4345VIvRhrsMa44546&",
    "expire": 1578478020,
    "dir": "images\/"
}

记得设置阿里云OSS跨域规则(不建议使用*,建议设置自己的可访问域名):

跨域规则

本作品采用《CC 协议》,转载必须注明作者和本文链接

分享开发知识,欢迎交流。qq957042781

13sai
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!