Skip to main content

Command Palette

Search for a command to run...

How to Upload Image to Aws-S3 Bucket in React Application

Published
4 min read
B

Software Engineer | Technical Writer | Content Creator

Introduction

In today's digital age, where visuals play a pivotal role in web applications, knowing how to seamlessly upload and manage images is a must-have skill for any React developer. Imagine empowering your applications with the ability to effortlessly store and retrieve images, all while leveraging the power and scalability of Amazon Web Services (AWS) S3. In this article, we'll embark on a journey through the world of React development, learning step by step how to harness the magic of AWS S3 to upload, store, and display images within your web applications. Buckle up, as we explore the art of image handling in React and unlock the potential of cloud-based storage.

Setup React Application

To ensure your local machine is ready to run a react application, you can set it up by simply doing this:

npx create-react-app my-app 
cd my-app
npm start

Install the AWS SDK

Aws sdk enables easy communication between the react app and aws s3 bucket.

npm install aws-sdk

Implementation

Create File Uploader

Firstly, we start by creating a file uploader, you can decide to use a package for it like Dropzone js or react-uploader. However, we will be using the default HTML input file uploader.


import React, { useState } from "react";


export default function App() {
  const [file, setFile] = useState(null);

  const handleFileUpload = (e) => {
    const file = e.target.files[0];
  };

  return (
    <div>
      <input
        type="file"
        accept=".png, .jpg, .jpeg"
        onChange={handleFileUpload}
      />
    </div>
  );
}

Install Bootstrap Library

We proceeded to install the react-bootstrap library, the reason why we are doing this is to use the progress bar to render the progress as we upload our file to aws-s3

npm install react-bootstrap bootstrap

We can import the react-bootstrap progress component, after which we pass a state (upload progress) to it, this state will be used to calculate the progress needed to render the progress bar. The code below depicts it.


import React, { useState } from "react";
import ProgressBar from "react-bootstrap/ProgressBar";

export default function App() {

  const [file, setFile] = useState(null);
  const [uploadProgress, setUploadProgress] = useState(0);


  const handleFileUpload = (e) => {
    const file = e.target.files[0];
  };


  return (
    <div>
      <input
        type="file"
        accept=".png, .jpg, .jpeg"
        onChange={handleFileUpload}
      />
      <ProgressBar animated now={uploadProgress} variant="success" />
    </div>
  );
}

Implement AWS SDK

Now we are going to modify the “handleFileUpload” function to upload our file to AWS-S3. In other to protect information, it's advisable to store one’s AWS credentials in a .env file. So, you can go ahead and store your AWS credentials in your env file. The code below demonstrates it.


import React, { useState } from "react";
import AWS from "aws-sdk";
import ProgressBar from "react-bootstrap/ProgressBar";
export default function App() {
  const [imageURL, setImageUrl] = useState("");
  const [uploadProgress, setUploadProgress] = useState(0);
  const handleFileUpload = async (e) => {
    const file = e.target.files[0];
    const S3_BUCKET = process.env.REACT_APP_S3_BUCKET_NAME;
    const REGION = process.env.REACT_APP_S3_BUCKET_REGION;
    const ACCESS_ID = process.env.REACT_APP_S3_ACCESS_ID;
    const SECRET_ACCESS_KEY = process.env.REACT_APP_S3_ACCESS_KEY;

    AWS.config.update({
      region: REGION,
      credentials: new AWS.Credentials({
        accessKeyId: ACCESS_ID,
        secretAccessKey: SECRET_ACCESS_KEY,
      }),
    });
    const s3 = new AWS.S3({
      params: { Bucket: S3_BUCKET },
      region: REGION,
    });

    const params = {
      Bucket: S3_BUCKET,
      Key: file.name,
      Body: file,
    };

    s3.putObject(params)
      .on("httpUploadProgress", (evt) => {
        const percentComplete = (evt?.loaded / evt?.total) * 100;
        setUploadProgress(percentComplete);
        return evt;
      })
      .promise();
    try {

      const data = await s3.upload(params).promise();
      const imageUrl = data?.Location;
      if (imageUrl) {
        setImageUrl(imageUrl);
      }
      alert("image uploaded successfully.");
    } catch (error) {
      console.error(error) 
      alert("there was an error");
      return error;
    }
  };
  return (
    <div>
      {imageURL && <img src={imageURL} alt="from bucket" />}
      <input
        type="file"
        accept=".png, .jpg, .jpeg"
        onChange={handleFileUpload}
      />
      <ProgressBar animated now={uploadProgress} variant="success" />
    </div>
  );
}

In the above code, we created a state variable “imageURL” to save the URL to the image in the s3 bucket. then we tracked the upload progress in the “.on” method using the “setUploadProgress” state function. This will then be used to render the animated progress bar in the browser. Finally, we passed the “imageURL” state which will be rendered as an image in the browser.

Conclusion

In this article, we have successfully:

  1. set up React-app

  2. install and initialize aws sdk

  3. calculate and render upload progress using a progress bar

  4. retrieved and rendered the uploaded image in the browser.

'

🤍 nice one

1
B

Thanks

More from this blog

Bankole Idris Blog

5 posts

A dynamic software engineer and prolific technical writer with a passion for crafting digital solutions that push boundaries.