vue.js - 从 Nuxt 上传到 AWS S3 存储桶时出现 500 内部服务器错误
问题描述
我正在尝试使用Nuxt 应用程序的 Vue 组件中的aws-sdk v3将文件上传到 AWS S3。
这是我上传它的方式。
<script>
export default {
...
methods: {
onSubmit(event) {
event.preventDefault()
this.addPhoto()
},
addPhoto() {
// Load the required clients and packages
const { CognitoIdentityClient } = require('@aws-sdk/client-cognito-identity')
const { fromCognitoIdentityPool } = require('@aws-sdk/credential-provider-cognito-identity')
const {
S3Client,
PutObjectCommand,
ListObjectsCommand,
DeleteObjectCommand,
} = require('@aws-sdk/client-s3')
const REGION = 'us-east-1' // REGION
const albumBucketName = 'samyojya-1'
const IdentityPoolId = 'XXXXXXX'
const s3 = new S3Client({
region: REGION,
credentials: {
accessKeyId: this.$config.CLIENT_ID,
secretAccessKey: this.$config.CLIENT_SECRET,
sessionToken: localStorage.getItem('accessToken'),
},
})
var file = this.formFields[0].fieldName
var fileName = this.formFields[0].fieldName.name
var photoKey = 'user-dp/' + fileName
var s3Response = s3.send(
new PutObjectCommand({
Bucket: albumBucketName,
Key: photoKey,
Body: file,
}),
)
s3Response
.then((response) => {
console.log('Successfully uploaded photo.' + JSON.stringify(response))
})
.catch((error) => {
console.log(
'There was an error uploading your photo: Error stacktrace' + JSON.stringify(error.message),
)
const { requestId, cfId, extendedRequestId } = error.$metadata
console.log({ requestId, cfId, extendedRequestId })
})
},
...
}
</script>
现在的问题是浏览器抱怨 CORS。
这是我在 AWS S3 上的 CORS 配置
解决方案
在存储桶策略中使用这个
{
"Version": "2008-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": [
"s3:GetObjectAcl",
"s3:GetObject",
"s3:PutObject",
"s3:PutObjectAcl",
"s3:ListMultipartUploadParts"
],
"Resource": "arn:aws:s3:::YOUR_BUCKET_NAME/*",
"Condition": {
"StringLike": {
"aws:Referer": "https://example/*"
}
}
}
]}
并使用您的存储桶区域
const s3 = new aws.S3({
apiVersion: 'latest',
accessKeyId: process.env.AWS_ACCESS_KEY_ID_CUSTOM,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY_CUSTOM,
region: 'us-west-1',
})
推荐阅读
- java - 没有发送短信,即使 toast 显示它已发送
- python - 有什么解决方案可以获取加载时间吗?
- firebase - 匿名身份验证用户的这个 Firebase/Firestore 安全规则是否安全?
- python - 使用日期时间列写入和读取行时获取不同的时区?
- r - R中特定版本的数据透视表(无聚合)
- ansible - ansible 根据 when 条件限制角色执行
- javascript - 正则表达式在 NodeJS 中不起作用?
- java - 在 ElasticSearch 中使用 Java API 时从 JSON DSL 构造 QueryBuilder?
- sql - 添加外键约束失败2
- kotlin-multiplatform - Kotlin Multiplatform Cocoapods 集成问题