AWS S3 file upload with progress bar using javascript sdk

AWS S3 file upload with progress bar using javascript sdk

Implementing a file upload system with a progress bar is a common requirement for modern web applications. Using the AWS SDK for JavaScript, you can handle large file uploads to S3 efficiently while providing real-time feedback to your users.

In this guide, we will walk through the steps to set up an AWS S3 file upload with a functional progress bar.

Prerequisites

Before starting, ensure you have the following:

  • An AWS account and an S3 bucket created.
  • CORS configured on your S3 bucket to allow uploads from your domain.
  • A file object (e.g., from an <input type="file">) stored in a variable like fileToBeUpload.

Step 1: Include the AWS SDK

Add the AWS SDK for JavaScript to the <head> section of your HTML file.

<script src="https://sdk.amazonaws.com/js/aws-sdk-2.207.0.min.js"></script>

Step 2: Initialize AWS Configuration

You can initialize the configuration in two ways. While you can use access keys directly, it is highly recommended to use an Identity Pool ID for better security in client-side applications.

Option A: Using Identity Pool ID (Recommended)

AWS.config.update({
  credentials: new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'YOUR_IDENTITY_POOL_ID'
  }),
  region: 'YOUR_AWS_REGION'
});

Option B: Using Access Keys

JavaScript

AWS.config.update({
  accessKeyId: 'YOUR_AWS_ACCESS_KEY',
  secretAccessKey: 'YOUR_AWS_SECRET_KEY',
  region: 'YOUR_AWS_REGION'
});

Step 3: Implement the Upload Logic

Now, let’s write the function to handle the upload and track progress. We will use the managed_upload class via bucket.upload(), which provides the httpUploadProgress event.

var bucketName = "YOUR_BUCKET_NAME";
var fileToBeUpload = document.getElementById('fileInput').files[0];
var filePath = "uploads/" + fileToBeUpload.name; // Destination path in S3

// Initialize the S3 Object
var bucket = new AWS.S3({
  apiVersion: "2006-03-01",
  params: { Bucket: bucketName },
});

var params = {
  Key: filePath,
  ContentType: fileToBeUpload.type,
  Body: fileToBeUpload,
  ContentDisposition: "attachment", // Optional: Forces download via public URL
};

/* Optional: Turn off timeout for large files */
AWS.config.httpOptions.timeout = 0;

// Start the upload
bucket.upload(params).on("httpUploadProgress", function (evt) {
  // Calculate percentage
  var uploaded = Math.round((evt.loaded / evt.total) * 100);
  console.log("File uploaded: " + uploaded + "%");
  
  // Update your UI progress bar here
  // document.getElementById('progressBar').style.width = uploaded + "%";
})
.send(function (err, data) {
  if (err) {
    console.log("Upload Error:", err.stack);
    alert("Failed to upload file.");
    return;
  }
  
  var fileUrl = data.Location;
  console.log("File uploaded successfully at:", fileUrl);
  alert("File is uploaded successfully!");
});

Important: S3 CORS Configuration

For the upload to work from a browser, you must enable CORS (Cross-Origin Resource Sharing) on your S3 bucket. Paste the following JSON into your bucket’s CORS configuration in the AWS Console:

[
    {
        "AllowedHeaders": ["*"],
        "AllowedMethods": ["PUT", "POST", "DELETE", "GET"],
        "AllowedOrigins": ["*"],
        "ExposeHeaders": ["ETag"]
    }
]

Conclusion

By following these steps, you can provide a seamless file upload experience for your users with real-time progress tracking. This method is scalable and leverages the power of AWS infrastructure directly from your JavaScript frontend.


Discover more from TCMHACK

Subscribe to get the latest posts sent to your email.

Tags:

Leave a Reply

Discover more from TCMHACK

Subscribe now to keep reading and get access to the full archive.

Continue reading