vue el-upload 上传到oss服务器
时间: 2023-11-07 21:56:14 浏览: 98
【JavaScript源代码】vue el-upload上传文件的示例代码.docx
可以使用第三方库 `ali-oss` 来完成该功能。具体操作可以参考以下示例代码:
```javascript
<template>
<el-upload
action=""
:before-upload="beforeUpload"
:on-success="onSuccess"
:on-error="onError"
:headers="{ 'x-oss-security-token': ossToken }"
:data="{ key: uploadedKey }"
:file-list="fileList"
multiple>
<el-button size="small" type="primary">上传文件</el-button>
</el-upload>
</template>
<script>
import OSS from 'ali-oss';
export default {
data() {
return {
fileList: [],
uploadedKey: '',
ossToken: '',
};
},
methods: {
async beforeUpload(file) {
// 获取 OSS Token
const response = await this.$http.get('https://example.com/get-oss-token');
if (response.data.code !== 0) {
this.$message.error('获取 OSS Token 失败');
return false;
}
this.ossToken = response.data.data;
// 构造上传参数
const client = new OSS({
region: 'oss-cn-hangzhou', // OSS Bucket 所在地域
accessKeyId: 'your-access-key-id',
accessKeySecret: 'your-access-key-secret',
stsToken: this.ossToken,
bucket: 'your-bucket-name',
});
const key = `uploads/${file.name}`;
this.uploadedKey = key;
const info = await client.multipartUpload(key, file, {
progress: (p) => {
console.log(`Progress: ${p}`);
},
meta: {
year: '2022'
}
});
},
onSuccess(response, file, fileList) {
this.$message.success('文件上传成功');
},
onError(error, response, file) {
this.$message.error('文件上传失败');
},
}
};
</script>
```
注意:上传过程中需要先获取阿里云的 OSS Token,并且在请求头中加上 `x-oss-security-token` 参数,同时需要设置 OSS 上传参数:Access Key ID,Access Key Secret,STS Token 和 Bucket Name。
阅读全文