我正在尝试使用express和multer将图像上传到s3。 我的前端是通过 AWS Amplify 部署的,后端是通过 Elastic Beanstalk 部署的。
问题是,当我尝试上传小于 1MB 的图像时,效果很好。但如果文件大于 1MB,我会收到以下错误。
4mb 图像文件上传到生产服务器时出现 HTTP 413 错误从源“我的后端路由”访问 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。
我以为问题出在Nginx限制主体文件大小上,所以我改变了它,但事实并非如此。
import aws from "aws-sdk";
import multer from "multer";
import multers3 from "multer-s3";
const s3 = new aws.S3({
accessKeyId: process.env.AMAZON_S3_ACCESS_KEY_ID,
secretAccessKey: process.env.AMAZON_S3_SECRET_ACCESS_KEY,
region: "ap-southeast-2",
});
const postUpload = multer({
storage: multers3({
s3,
bucket: 'bucket name'///,
acl: "public-read",
metadata: (req, file, cb) => {
cb(null, { fileName: file.fieldname });
},
key: (req, file, cb) => {
cb(null, Date.now().toString());
},
}),
limits: { fileSize: 5242880 },
});
export const postUploadMiddleware = postUpload.array("files", 6);
export const uploadController = (req, res) => {
console.log(req.files);
const { files } = req;
res.json(files);
};
///////
app.post("/api/post/upload", postUploadMiddleware, uploadController);
这是我的请求标头,出现错误
POST /api/post/upload HTTP/1.1
Host: 'host name'///
Connection: keep-alive
Content-Length: 1195613
Accept: application/json, text/plain, */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryLrPlKnjaQZwy7M1Z
Origin: 'frontend url'///
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: 'frontend url'///
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,ko-KR;q=0.8,ko;q=0.7
有谁可以帮忙吗?
res.setHeader('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT');
res.setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept, Authorization');
是问题的解决方案。我还建议您检查 S3 设置中的 CORS。应该是这样的:
[
{
"AllowedHeaders": [],
"AllowedMethods": [
"GET",
"POST",
"PUT",
"DELETE"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [],
"MaxAgeSeconds": 3000
}
]
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"HEAD",
"POST",
"PUT"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [
"ETag",
"x-amz-meta-custom-header"
],
"MaxAgeSeconds": 3000
}
]
希望这有帮助。