2

I am a newbie on Amazon S3. I am facing the issue regarding uploading the image directly from frontend to an Amazon S3 bucket. I viewed many tutorials but there is no proper explanation about uploading image directly to s3. Need a solution to it using React js only.

2
  • Look at AWS Amplify options or build a backend that your front-end can make API calls to (to request an S3 pre-signed URL that the front-end can then upload directly to using request/axios or HTTPS POST). Commented Apr 20, 2022 at 13:42
  • You can use the AWS SDK for JavaScript v3 from your React App as well without using Amplify Commented Apr 20, 2022 at 14:09

3 Answers 3

1

One solution is to import the AWS SDK for JavaScript v3 into your React app and then use the s3Client within your React app. There are instructions on how to use this SDK in a React app here:

Getting started in React Native

Here is more content that shows HOW TO use the AWS SDK for JavaScript in a React App:

Integrate the AWS SDK for JavaScript into a React App

To upload an object to an Amazon S3 bucket using the s3Client, use this code example:

// Import required AWS SDK clients and commands for Node.js.
import { PutObjectCommand } from "@aws-sdk/client-s3";
import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module.

// Set the parameters.
export const bucketParams = {
  Bucket: "BUCKET_NAME",
  // Specify the name of the new object. For example, 'index.html'.
  // To create a directory for the object, use '/'. For example, 'myApp/package.json'.
  Key: "OBJECT_NAME",
  // Content of the new object.
  Body: "BODY",
};

// Create and upload the object to the S3 bucket.
export const run = async () => {
  try {
    const data = await s3Client.send(new PutObjectCommand(bucketParams));
    return data; // For unit tests.
    console.log(
      "Successfully uploaded object: " +
        bucketParams.Bucket +
        "/" +
        bucketParams.Key
    );
  } catch (err) {
    console.log("Error", err);
  }
};
run();

You can view more Amazon S3 code examples for the the s3Client in the AWS Github repo:

Amazon S3 JavaScript SDK v3 code examples

Sign up to request clarification or add additional context in comments.

3 Comments

need complete code for react
the above code is the complete Code to upload an object using the JS S3Client. You need to follow the instructions that I linked to, hook the AWS SDK for JavaScript into your React project and then code the app logic using the S3Client
this answer only shows how to use the aws sdk code alone in the example provided in the docs but doesnt answer the question of how you use it with react and specifically an image upload and since stack overflow is for providing direct answers to question i didnt find the answer complete or beyond what i found already in the docs myself
0

Using only react will expose your s3 credentials instead use express to generate signed URL to upload files.

See this videos https://www.youtube.com/watch?v=yGYeYJpRWPM&ab_channel=SamMeech-Ward

1 Comment

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
0

import AWS from "aws-sdk";
import { Buffer } from "buffer";
Buffer.from("anything", "base64"); 
window.Buffer = window.Buffer || require("buffer").Buffer;

const handleUpload = async () => {
    const S3_BUCKET = process.env.REACT_APP_AWS_BUCKET;
    // S3 Region
    const REGION = process.env.REACT_APP_AWS_REGION;
    // S3 Credentials
    AWS.config.update({
      accessKeyId: process.env.REACT_APP_AWS_ACCESS_KEY_ID,
      secretAccessKey: process.env.REACT_APP_AWS_SECRET_ACCESS_KEY,
    });
    const s3 = new AWS.S3({
      params: { Bucket: S3_BUCKET },
      region: REGION,
    });

    // Set the S3 object parameters
    const params = {
      Bucket: S3_BUCKET,
      Key: "directoryName/" + selectFile?.name,
      Body: selectFile,
    };

    // Upload the file to S3
    s3.upload(params, (err, data) => {
      if (err) {
        console.error("Error uploading file:", err);
      } else {
        console.log("File uploaded successfully:", data);
        
        //  Console.log
        //  {
        //    bucket: "myBucket",
        //    key: "directoryName/test-image.jpg",
        //    location: "https://myBucket.s3.amazonaws.com/directoryName/test-file.jpg"
        //  }
      }
    });
  };

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
this uses v2 of the aws sdk, not the latest v3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.