React Amazon S3 - Image uploaded to S3 Bucket CORS problem - File Saver

484 Views Asked by At

I have a problem with images being uploaded to the S3 bucket. I can upload them on S3 bucket without any problems, but I have a problem getting them from the S3 with signed URL

What works

When I upload PDF file on S3 bucket, and when I want to get them back, and to download them with FileSaver package in React.js, everything works perfectly fine, without any problems. Here are the response headers from PDF file:

enter image description here

Code

We are also using Strapi for backend and this is how we get presigned URL for upload and signedURL for "download".

module.exports = {
  async getSignedUrlUpload(ctx) {
    const bucketParams = {
      Bucket: process.env.S3_BUCKET_NAME,
      Key: ctx.request.query.fileName,
    };
    const uploadUrl = await getUploadUrl(bucketParams);
    return { uploadUrl };
  },
  async getSignedUrlDownload(ctx) {
    const bucketParams = {
      Bucket: process.env.S3_BUCKET_NAME,
      Key: ctx.request.query.fileName,
    };
    const downloadUrl = await getDownloadUrl(bucketParams);
    return { downloadUrl };
  },
};

getSignedURLUpload and getSignedURLDownload:

const getUploadUrl = async (bucketParams) => {
  try {
    // Create a command to put the object in the S3 bucket.
    const command = new PutObjectCommand(bucketParams);
    // Create the presigned URL.
    const signedUrl = await getSignedUrl(s3Client, command, {
      expiresIn: 3600,
    });
    return signedUrl;
  } catch (err) {
    console.log("Error creating presigned URL", err);
  }
  
};

const getDownloadUrl = async (bucketParams) => {
  try {
    const command = new GetObjectCommand(bucketParams);

    // Create the presigned URL.
    const signedUrl = await getSignedUrl(s3Client, command, {
      expiresIn: 3600,
    });
    return signedUrl;
  } catch (err) {
    console.log("Error creating presigned URL", err);
  }
  
};

What I want to do

When I am using the FileSaver saveAs method to download the files from the signedURL I get a error when downloading images but do not get the error when downloading the PDF file

enter image description here

enter image description here

1

There are 1 best solutions below

0
Nir Alfasi On

Looks like you're getting CORS error. Assuming you're using express in the backend try using CORS middleware to fix the issue:

https://expressjs.com/en/resources/middleware/cors.html