无法上传文件到私有aws S3桶



我正试图将文件上传到aws S3与nodeJS服务器和React客户端应用程序。我是新的aws,所以我想我做错了什么。我已经创建了一个完全私有的备份,以便只有应用程序可以访问文件。问题是,当我想上传一个文件,我需要得到链接myBucket。getSignedUrl(),以便上传它。当我这样做并将其发送到前端时,前端通过我要上传的文件获取到S3的链接,问题是它返回以下错误:

获取at的权限的https://atlasworld-progress.s3.amazonaws.com/IMG_20210202_100322.jpg?AWSAccessKeyId=AKIAZGHWWSFL5XOWPRXJ& - type = % 2 fjpeg&amp形象;到期= 1633937718,签名= o8S8MQQ3fVdONePGOT4a5ic7CcU % 3 d '来自原产地'http://localhost:3000'已被CORS策略阻止:预起飞请求响应未通过访问控制检查:否"访问-控制-允许-起源"标头出现在请求上资源。如果不透明的响应满足您的需求,请设置请求模式为'no-cors'来获取禁用CORS的资源。

这是aws的配置文件:

import AWS from 'aws-sdk'
AWS.config.update({
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_KEY
})
const S3_BUCKET ='atlasworld-progress';
const REGION =process.env.AWS_REGION;
const URL_EXPIRATION_TIME = 60; // in seconds
const myBucket = new AWS.S3({
params: { Bucket: S3_BUCKET},
region: REGION,
})
export const generatePreSignedPutUrl = async (fileName, fileType) => {
const url = await myBucket.getSignedUrl('putObject', {
Key: fileName,
ContentType: fileType,
Expires: URL_EXPIRATION_TIME
});
return url;
}

在express控制器中,它只是将generatePreSignedPutUrl()函数生成的链接返回给客户端。以下是React中前端函数的代码:

const [frontPhoto, setFrontPhoto] = useState();
const upload = async (e) => {
e.preventDefault();
await JWT.checkJWT();
const requestObject = {
fileName: frontPhoto.name,
fileType: frontPhoto.type,
token: JWT.getToken()
};
axiosReq.post(`${serverPath}/prepare_s3`, requestObject).then((res) => {
//the following fetch is the one that fails
fetch(res.data, {
method: "PUT",
body: frontPhoto,
}).then((res) => {
console.log(res);
});
});
}

如果有人知道发生了什么事,我会很感激你的帮助。

我还想问S3是否一次只能上传一个文件,或者在一次抓取中可以上传不同的文件。

谢谢!

我想这说明了一切:

从源'http://localhost:3000'读取已被CORS策略阻止

你需要熟悉CORS。如果你想让它工作,那么你需要从AWS启用CORS。

这是nginx配置问题,您必须增加client_max_body_size在nginx.conf

步骤:

  1. 通过ssh连接到你的Beanstalk/EC2实例:

    ssh -i <key.pem> <ec2-user>@<host>

  2. 以超级用户登录:

    $ sudo su

  3. 编辑nginx.conf
  4. nano /etc/nginx/nginx.conf

  5. 将这行添加到http块

    client_max_body_size 50M;

  6. 保存文件

  7. 重启nginx服务

    $ service nginx restart

示例NGINX配置文件

# Elastic Beanstalk Nginx Configuration File
user  nginx;
worker_processes  auto;
error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;
events {
worker_connections  1024;
}
http {
client_max_body_size 50M;           --------- add this line
include       /etc/nginx/mime.types;
default_type  application/octet-stream;
access_log    /var/log/nginx/access.log;
log_format  healthd '$msec"$uri"$status"$request_time"$upstream_response_time"$http_x_forwarded_for';
include       /etc/nginx/conf.d/*.conf;
include       /etc/nginx/sites-enabled/*;
}

最新更新