Upload Files to S3

Now each user gets her own folder inside the S3 bucket, we can now upload files from our application front-end and validate the access.

function getUserId(){
    const key = `aws.cognito.identity-id.${identityPoolId}`;
    return cognitoUser.pool.storage[key];
}

function uploadFile(){
    var files = document.getElementById("file-upload").files;
    if (!files.length) {
        return alert("Please choose a file to upload.");
    }
    var file = files[0];
    var fileName = file.name;    
    var fileKey = `users/${getUserId()}/${fileName}`;

    var upload = new AWS.S3.ManagedUpload({
        params: {
            Bucket: S3DocBucket,
            Key: fileKey,
            Body: file        
        }
    });

    upload.promise()
    .then((data) => {
        // file uploaded
    },(err) => {
        // error uploading the file
    });
}

AWS S3 is an Object Storage service. Unlike the regular file system, S3 stores the data in a different way, and you can consider it's a Key/Value store as well. In the above example, we are uploading a file with Key=users/<userId>/filename and Value=<file data>.

Last updated