AWS S3: Upload a File to S3 Using Javascript in the Browser and Show a Progress Bar

10/4/2019 7:23:00 PM

Upload a file to an S3 bucket directly from the browser, without the need to run a server, and show a progress bar for the upload. You will need to create a Cognito Identity with an unauth role to do this.

Create a New S3 Bucket

Bucket Policy


<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedHeader>*</AllowedHeader>
    <AllowedMethod>PUT</AllowedMethod>
</CORSRule>
</CORSConfiguration>

Cognito Unauth Permission


{
	"Effect": "Allow",
	"Action": [
		"s3:PutObject"
	],
	"Resource": [
		"arn:aws:s3:::my-bucket/*"
	]
}

Javascript


//aws
var var__aws__cognito_pool_id = "us-east-1:??????????????????POOL-ID";
var var__aws__region = "us-east-1";
var var__aws__s3;
var var__aws__s3__upload_bucket = "my-bucket";


AWS.config.region = var__aws__region;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: var__aws__cognito_pool_id,
});

var__aws__s3 = new AWS.S3();




//$("#form__aws__s3__upload_file").submit(function (e)
$(document).on("submit", "#form__aws__s3__upload_file", function (e)
{
    e.preventDefault();  //prevent form from submitting
    console.log("#form__aws__s3__upload_file: submit");

    
    var fileInput = $("#form__aws__s3__upload_file__input");    
    if (fileInput.length != 1 || fileInput[0].files.length != 1)
    {
        console.log("no file selected");
        return;
    }


    //show progress bar
    $("div.upload-progress").show();


    var file = fileInput[0].files[0];    
    var file_name = file.name.toString();

    var s3_key = "";
    s3_key = "uploads/";
    s3_key += Date.now();        
    s3_key += "-";
    s3_key += file_name;


    var upload_params = {
        Bucket: var__aws__s3__upload_bucket,
        Key: s3_key,
        Body: file
    };



    var__aws__s3.upload(upload_params, function (err, data)
    {
        console.log(err);
        console.log(data);

        //$("div.upload-progress").hide();

        if (err)
        {
            console.log('There was an error uploading your file: ', err.message);
        }
        else
        {
            console.log("Upload Success");
        }
    })
        .on('httpUploadProgress', function (evt)
        {
            try
            {
                console.log('Progress:', evt.loaded, '/', evt.total);

                var percent_complete = evt.loaded / evt.total;
                percent_complete = percent_complete * 100;
                console.log(percent_complete);

                $("div.upload-progress div").css("width", percent_complete.toString() + "%");
            }
            catch (err)
            {
                console.log(err);
            }
        });

});

Html


<h1>AWS S3: Upload a File</h1>

<form id="form__aws__s3__upload_file">
    <div class="form-group">
        <label class="control-label">Choose the File</label>
        <input id="form__aws__s3__upload_file__input" type="file" class="form-control" style="height:auto" />
        <span class="text-danger"></span>
    </div>
    <input type="submit" value="Submit" class="btn btn-primary" />
</form>
<div class="upload-progress"><div></div></div>