Site icon Satish Gandham

How to Upload a File/Image Directly to S3 using presignedPost policy

Problem: Find an efficient and secure way to upload files to S3.

Method 1: Pass the file to the server and handle the S3 upload on the server.

Method 2: Upload the file directly from the client aka browser to S3.

Problem with method #1 is it’s not very efficient, you are unnecessarily wasting the server resources and bandwidth.

Method #2 is not secure, as you have to pass your AWS credentials to the client.

The efficient and secure way to do this is via a presigned URL or by using a presigned post policy.

A presigned URL gives you access to the object identified in the URL, provided that the creator of the presigned URL has permissions to access that object. That is, if you receive a presigned URL to upload an object, you can upload the object only if the creator of the presigned URL has the necessary permissions to upload that object.

Problem with a presigned url is you can use it only to upload one file, since we need a way to upload multiple files, we are going with presigned post.

We will be using aws node sdk to generate the presigned post policy.

Generate Presigned Post Policy With on NodeJS

npm install aws-sdk

Configure the SDK at the start of the application like this. In meteor this code would go in Meteor.startup

import AWS from 'aws-sdk/global';
const settings = {
     "accessKeyId": "PUT_YOUR_ACCESS_KEY",
     "secretAccessKey": "PUT_YOUR_ACCESS_SECRET",
     "bucket": "PUT_YOUR_BUCKET_NAME",
     "region": "PUT_YOUR_BUCKET_REGION" //ex: ap-south-1
}
AWS.config = new AWS.Config(settings );

We hardcoded the key and secret above, ideally you should set them in the environment variables on your server.

Your actual function to return the presigned post would be

import S3 from 'aws-sdk/clients/s3';
import Promise from 'promise';


 

 

Exit mobile version