一、在上傳之前,需要先獲取到AWS的S3服務(wù)的Access key ID和Secret access key
二、代碼代碼:
<template>
<div class="upload">
<!-- 我這里使用的是el-upload的http-request自定義上傳事件,action用不上,但是不寫值會報(bào)錯(cuò),所以我也寫上了,但是其實(shí)并沒有用到~ -->
<el-upload :show-file-list="false" drag :http-request="handleFileChange" class="upload-demo"
action="your upload address" multiple>
<el-button><i class="el-icon-upload"></i>Upload</el-button>
</el-upload>
</div>
</template>
<script>
// 需要安裝aws-sdk 再引入哦~
import AWS from "aws-sdk";
export default {
data() {
return {
s3: new AWS.S3({
// AWS 認(rèn)證相關(guān)
apiVersion: "2006-03-01",
accessKeyId: "填自己的",
secretAccessKey: "填自己的",
region: "填自己的",
}),
videoUpload: null,
videoLoading: false, // 防止再次點(diǎn)擊
videoFileName: "", // 文件名稱
videoSuffix: "", // 文件后綴
};
},
methods: {
handleFileChange(e) {
var that = this;
let file = e.target.files[0];
console.log("file change", file);
if (file) {
that.videoFileName = file.name;
that.videoLoading = true;
that.videoSuffix = that.videoFileName.split(".")[1];
var key = new Date().getTime() + "_" + "." + that.videoSuffix;
var params = {
Bucket: "填自己的", // 存儲桶名稱
Key: key, // 文件名,重名會覆蓋
Body: file,
};
that.videoUpload = that.s3.upload(params, function (err, data) {
if (err) {
console.log("發(fā)生錯(cuò)誤:", err.code, err.message);
that.videoLoading = false;
} else {
console.log("上傳成功, 返回結(jié)果");
console.log(data);
console.log(data.Location); //上傳文件在S3的位置
}
});
}
},
},
};
</script>
別忘記安裝AWS.S3??!
npm i aws-sdk // 安裝aws-sdk
三、如果上傳失敗,報(bào)此錯(cuò)誤:ETagMissing No access to ETag property on response. Check CORS configuration to expose ETag header.
解決方案:找到配置的存儲桶——權(quán)限——跨源資源共享(CORS),配置如下
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"PUT",
"POST",
"DELETE"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [
"ETag",
"x-amz-server-side-encryption",
"x-amz-request-id",
"x-amz-id-2"
],
"MaxAgeSeconds": 3000
},
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"PUT",
"POST",
"DELETE"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [
"ETag",
"x-amz-server-side-encryption",
"x-amz-request-id",
"x-amz-id-2"
],
"MaxAgeSeconds": 3000
},
{
"AllowedHeaders": [],
"AllowedMethods": [
"GET"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [
"ETag",
"x-amz-server-side-encryption",
"x-amz-request-id",
"x-amz-id-2"
],
"MaxAgeSeconds": 3000
}
]
參考文章:文章來源:http://www.zghlxwxcb.cn/news/detail-572185.html
https://www.jianshu.com/p/2bd8717d2d89文章來源地址http://www.zghlxwxcb.cn/news/detail-572185.html
到了這里,關(guān)于Vue element ui + AmazonS3上傳文件功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!