5.1 Transferring files using standard AWSS3 SDK

Add the following to the scripts:

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

5.1.1 Initialize the S3 object

Pass your Amazon credentials to the secureS3 constructor.

let isConfigUpdate = false;
let s3;

try {

    if (!window.AWS) {
        return
    }
    
    if (!isConfigUpdate) {
        window.AWS.config.update(({ region: <region> }));
        isConfigUpdate = true;
    }

s3 = new window.AWS.S3({
    credentials: new window.AWS.Credentials({
    apiVersion: "<apiVersion>",
    accessKeyId: "<accessKeyId>",
    secretAccessKey: "<secretAccessKey>",
    signatureVersion: "<signatureVersion>",
    region: "<region>",
    bucket: "<bucket>"
        })
    });
}
catch (error) {
    console.log(error)
}

5.1.2 Upload a File to Amazon S3

To upload a file to S3, instantiate a s3 object. Call upload() and pass the following parameters:

let lockedBase64ToArrayBuffer = "<fileToUploadInBase64Format>";
let fileType = "<fileType>";
let fileName = <"fileName>";
let bucket = "<bucketName>";

await this.uploadToS3Bucket(
        lockedBase64ToArrayBuffer, 
        (progress) => { console.log(progress) }, 
        fileType, 
        fileName,
);  
        
uploadToS3Bucket = async (stream, progressCallBack, fileType, fileName) => {
        try {
            let uploadItem = await s3.upload({
                Bucket: bucket,
                Key: fileName,
                ContentType: fileType,
                Body: stream
            }).on("httpUploadProgress", function (progress) {
                console.log("progress=>", progress)
                progressCallBack(this.getUploadingProgress(progress.loaded, progress.total));
            }).promise();
            console.log("uploadItem=>", uploadItem);
            return uploadItem;
        }
        catch (error) {
            console.log(error)
        }
    } 

5.1.3 Download a File from Amazon S3

To download a file to S3, instantiate a s3 object. Call getObject() and pass the following parameters:

await s3.getObject(
      { 
          Bucket: "<YourBucketName>", 
          Key: "<YourFileName>" 
      },
    async function (error, data) {
        if (error != null) {
            alert("Failed to retrieve an object: " + error);
        } else {
            //alert("Loaded " + data.ContentLength + " bytes");
            // do something with data.Body
            console.log("Downloaded Image Data :", data);
            console.log("Array ", data.Body);
        }
    }
);

5.1.4 Tracking S3 Transfer Progress

To get the progress of a download or upload, use the following code snippets. For example:

getUploadingProgress = async (uploadSize, totalSize) => {
        let uploadProgress = (uploadSize / totalSize) * 100;
        return Number(uploadProgress.toFixed(0));
}    

Last updated