Upload to AWS s3 from the browser

Upload to AWS s3 from the browser

Most of the web application has the necessity to upload the media or file to their server. Usually, we use an API to send the file to the API server and from there we used to upload the file to the s3. AWS has simplified the work of a programmer by introducing SDK for different platform.
 

In this writing, we’ll look into one of the ways to upload the media to s3 from the browser. To achieve our goal we need to do a write a bunch of code on both the server side and the front-end. Let’s get started with server-side. In this example, we will be using node.js as the backend.

 

Let’s get started with the server-side:

var AWS = require('aws-sdk');
AWS.config.accessKeyId = {AWS_ACCESS_KEY};
AWS.config.secretAccessKey = {AWS_SECRET_KEY};
AWS.config.region = {AWS_REGION};
const s3 = new AWS.S3({signatureVersion:'v4');
// function to generate the signed url
var generateSign = function(params, callback) {
     const s3Params = {
       Bucket: {AWS_BUCKET_NAME},
       Key: {FILE_NAME},
       ContentType: {FILE_TYPE},
     };
     s3.getSignedUrl('putObject', s3Params, (error, signedUrl) => {
       if (error) return callback(error);
       return callback(error, signedUrl);
     });
};

 

To explain the above code in simple words. Install aws-sdk and set the required config. Inside the function block, we are forming the required params to get the signed URL. Also, replace with required values in place of AWS_ACCESS_KEY, AWS_SECRET_KEY, AWS_REGIONAWS_BUCKET_NAME, FILE_NAMEFILE_TYPE.

 

NOTE: We’re generating the signed URL for putObject as we’ll be uploading the file from the browser with the PUT method.

 

Here is what we need to do in the front-end:

In this example, we’re using axios to send request from the browser. Once we get the signed URL for the file, we can upload the file from the browser.

return axios({
  url: {SIGNED_URL},
  method: 'put',
  data: {FILE},
  })
  .then(response => response.data)
  .catch(err => error(err));
})

SIGNED_URL Pass the URL generated from the server.

FILE Pass an object which we need to upload.

The respective success and failure will be returned in the then or catch block.

 

Epilogue:

  • Also, check whether CORS configuration is added in the respective s3 bucket where we’re uploading.

Reference:

Share The Blog

 

Leave a Reply

Your email address will not be published. Required fields are marked *