I want to upload the image that the user uploaded to the input tag to S3 bucket, but the CORS error is not resolved.
my Bucket's CORS Policy
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"PUT",
"POST",
"HEAD"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [
"x-amz-server-side-encryption",
"x-amz-request-id",
"x-amz-id-2"
],
"MaxAgeSeconds": 3000
}
]
and Bucket Policy
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicListGet",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:PutObject",
"s3:GetObjectAcl",
"s3:GetObject",
"s3:ListBucket",
"s3:DeleteObject",
"s3:PutObjectAcl"
],
"Resource": [
"arn:aws:s3:::project-name",
"arn:aws:s3:::project-name/*"
]
}
]
}
I think the cause is the react code, but i can't find it......
import { useState } from 'react';
import AWS from 'aws-sdk';
const S3UploadImage = () => {
const [imageFile, setImageFile] = useState<File | null>(null);
const REGION = import.meta.env.VITE_AWS_S3_APP_REGION;
const S3_BUCKET = import.meta.env.VITE_AWS_S3_BUCKET_NAME;
AWS.config.update({
accessKeyId: import.meta.env.VITE_AWS_S3_ACCESS_ID,
secretAccessKey: import.meta.env.VITE_AWS_S3_ACCESS_KEY,
region: REGION,
});
const myBucket = new AWS.S3({
params: { Bucket: S3_BUCKET },
region: REGION,
});
const handleFileInput = async (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files) {
const file = e.target.files[0];
const fileExt = file.name.split('.').pop();
if (fileExt !== 'jpg' && fileExt !== 'jpeg' && fileExt !== 'svg' && fileExt !== 'png') {
alert('only jpg, svg, png are available');
return;
}
setImageFile(file);
}
};
const handleUploadBtn = () => {
if (imageFile) {
const params = {
ACL: 'public-read',
Body: imageFile,
Bucket: S3_BUCKET,
Key: 'TechImages/' + imageFile.name,
};
myBucket.putObject(params).send((err) => {
if (err) console.log(err);
return;
});
} else alert('please choose file');
};
return { handleFileInput, handleUploadBtn };
};
export default S3UploadImage;
my testing component is
const Test = () => {
const { handleFileInput, handleUploadBtn } = S3UploadImage();
return (
<>
<TestInput type="file" onChange={handleFileInput}></TestInput>
<Btn onClick={handleUploadBtn}> submit </Btn>
</>
);
};
export default Test;