阿里雲 OSS 簽名上傳(結合 elementUI)

sai0556發表於2020-01-15

原理:從服務端獲取簽名,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,公眾號:愛好歷史的程式設計師。

相關文章