一、在上传之前,需要先获取到AWS的S3服务的Access key ID和Secret access key
二、代码代码:
<template>
<div class="upload">
<!-- 我这里使用的是el-upload的http-request自定义上传事件,action用不上,但是不写值会报错,所以我也写上了,但是其实并没有用到~ -->
<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 认证相关
apiVersion: "2006-03-01",
accessKeyId: "填自己的",
secretAccessKey: "填自己的",
region: "填自己的",
}),
videoUpload: null,
videoLoading: false, // 防止再次点击
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("发生错误:", err.code, err.message);
that.videoLoading = false;
} else {
console.log("上传成功, 返回结果");
console.log(data);
console.log(data.Location); //上传文件在S3的位置
}
});
}
},
},
};
</script>
别忘记安装AWS.S3!!
npm i aws-sdk // 安装aws-sdk
三、如果上传失败,报此错误:ETagMissing No access to ETag property on response. Check CORS configuration to expose ETag header.
解决方案:找到配置的存储桶——权限——跨源资源共享(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
}
]
参考文章:文章来源:https://www.toymoban.com/news/detail-572185.html
https://www.jianshu.com/p/2bd8717d2d89文章来源地址https://www.toymoban.com/news/detail-572185.html
到了这里,关于Vue element ui + AmazonS3上传文件功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!