话不多说,直接上代码。
<template>
<div>
<input type="file" @change="handleFileChange">
</div>
</template>
<script>
import AWS from 'aws-sdk';
export default {
data () {
s3: new AWS.S3({ // AWS 认证相关
apiVersion: '2006-03-01',
accessKeyId: '填自己的',
secretAccessKey: '填自己的',
region: '填自己的'
}),
videoUpload: null,
videoLoading: false, // 防止再次点击
videoProgress: 0 ,// 进度条
videoFileName: "", // 文件名称
videoSuffix: "", // 文件后
},
methods: {
handleFileChange(){
var that = this;
let file = e.target.files[0]
console.log('file change',file);
if(file){
that.videoFileName = file.name;
that.videoLoading = true;
that.videoProgress = 0;
that.videoSuffix = that.videoFileName.split(".")[1];
var key = new Date().getTime() + "_" + Math.random().toFixed(2) + "." + 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的位置
}
});
}else{
}
}
}
}
</script>
如果上传失败,报此错误:ETagMissing No access to ETag property on response. Check CORS configuration to expose ETag header.
解决方案:找到配置的存储桶——权限——跨源资源共享(CORS),配置如下
[{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"PUT",
"POST",
"DELETE"
],
"AllowedOrigins": [
"可以输入你当前上传功能所在的域名地址,如www.baidu.com"
],
"ExposeHeaders": [
"ETag",
"x-amz-meta-custom-header"
]
}]
上传完成!