Introduction:

S3 (Simple Storage Service) is a cloud storage platform for handling file uploads, especially images. Whenever a mobile app or web application is developed, we need a reliable image storage solution. S3 provides scalable, secure and cost-effective storage with high performance.
In this blog, we can see the different approaches to upload images to s3.

Why S3 storage?
This storage has lot of advantages:
Scalability: Handles millions of images
Durability: Has 99.99% data durability
Global CDN Integration: Very easily intehrated for fast image delivery
Cost-Effective: Pay only for what we use
Security: Fine-grained access control and encryption options
Integration: Works without any issues with other AWS services

Prerequisites:
Before we start integrating, we must ensure we are having the following details.

  1. An AWS account with s3 access
  2. AWS Credentials (Access Key ID & secret Access key)
  3. An S3 bucket created

Direct Upload from client-Side

This can be easily done by using simple java script utility function.

Step 1: Install AWS SDK. The command is npm install aws-sdk.

Step 2:
Basic Client side Upload:

Import the installed package.
import AWS from ‘aws-sdk’;

We have to configure AWS.

AWS.config.update({
accessKeyId: ‘YOUR_ACCESS_KEY’,
secretAccessKey: ‘YOUR_SECRET_KEY’,
region: ‘REGION USED WHILE CREATION’
});

Step 3:
const s3 = new AWS.S3();

function uploadImage(file, bucketName, key) {
const params = {
Bucket: bucketName,
Key: key,
Body: file,
ContentType: file.type,
ACL: ‘public-read’ // Make the file publicly accessible
};

return s3.upload(params).promise();
}

const result = await uploadImage(file, ‘your-bucket-name’, images/${Date.now()}-${file.name});

If we call the function with the required parameters we can save the images in S3 bucket we have created.

Server-Side Upload:

Server-side uploads can be done by using Node.js or Express. It is a better security process.
Step 1:
Setting Up Express Server.

Step 2:

Upload images.

Predesigned URLs:

This is a more secure way to allow direct client uploads without exposing AWS credentials.

Here attached steps to create a URL on both client and server side respectively.

Advanced Features:

  • We can also advanced features like Image optimization and resizing for better performance.
  • We can also include progress tracking during file upload process.
  • Multiple file uploads are handled.
  • Improved error handling and validation

Best Practices:

  1. Considering security purposes we should always store keys as environemntal variables and should not use directly in our code either client-side or server-side.
  2. We should follow performance optimization methods.
  3. To track the progress we should include the error handling techniques.

Using these methods, we can upload images to cloud storage and can preserve them.

Leave a Reply