代碼參考:
- 繼承 uplaod 重寫http-request, 定義新的上傳組件 OSSUpload
<script>
import {Upload} from 'element-ui';
import OSS from 'ali-oss';
import {getToken} from 'api/oss';
export default {
name: "OSSUpload",
mixins: [Upload],
props: {
ossOnSuccess: {
type: Function,
default: Function
},
httpRequest: {
type: Function,
default: async params => {
try {
const {result} = await getToken();
const ossClient = new OSS({
region: "oss-cn-shanghai",
accessKeyId: result.AccessKeyId,
accessKeySecret: result.AccessKeySecret,
stsToken: result.SecurityToken,
bucket: result.bucket
});
const file = params.file;
ossClient.put(file.name, file).then(val => {
if (val.res.statusCode === 200) {
params.onSuccess(val);
}
}, err => {
params.onError(err);
});
} catch (e) {
params.onError(e);
}
}
},
},
methods: {}
}
</script>
複製代碼
- 使用組件
<template>
<el-main>
<h1>Hello OSS !!!</h1>
<OSSUpload action="alioss"
list-type="picture-card"
:file-list="picList"
:on-success="handleSuccess">
<i class="el-icon-plus"></i>
</OSSUpload>
</el-main>
</template>
<script>
import {Upload} from 'element-ui';
import OSSUpload from "./OSSUpload";
export default {
name: "oss",
components: {OSSUpload},
mixins: Upload,
data() {
return {
picList: []
};
},
methods: {
handleSuccess(...params) {
if (params[0]) {
console.log("上傳成功", params[0]);
}
}
}
}
</script>
複製代碼