I'm trying to upload a local file to an AWS S3 bucket. I use the fetch api PUT method. The URL is pre-signed by S3. I am encountering a CORS issue.
I have no problem uploading ~30kb; it happens with a single request.
But if I upload a 2mb file, it requires 2 requests. The first is preflight with option method and results in 200 OK
. But the second is the "real" request and it fails. I have set the CORS policy in S3 as "Access-Control-Allow-Origin":"*"
. The response header of the preflight request has "Access-Control-Allow-Origin"
, but real request doesn't.
My code is simple:
let command = new PutObjectCommand({
Body: "selectedfile",
Bucket: "my bucket",
Key: "filename"
});
let signedurl = await getSignedUrl({
region:"myregion",
credentials:{accessKeyId:"mykey",secretAccessKey:"mykey"}}, command, {expiresIn:3600}
);
let response = await fetch(signedurl, {method: "PUT", body: "selectedfile"});
Does anyone have a clue to fix this CORS issue?
Before you can use presigned URLs to upload to S3, you need to define a CORS policy on the S3 bucket so that web clients loaded in one domain (eg localhost or cloudfront) can interact with resources in the S3 domain. Setting a CORS policy on an S3 bucket is not complicated; however, if you do get it wrong, you can often solve it with the suggestions mentioned in this CORS troubleshooting guide: https://docs.aws.amazon.com/AmazonS3/latest/dev/cors-troubleshooting.html
I also suggest reading this blog:
https://aws.amazon.com/blogs/media/deep-dive-into-cors-configs-on-aws-s3-how-to/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.