Created
September 14, 2019 14:31
-
-
Save nathanbarrett/a0847ce61adaaf5548a5ef64a68c2582 to your computer and use it in GitHub Desktop.
An easy wrapper for browser S3 uploads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import S3 from "aws-sdk/clients/s3"; | |
const s3 = new S3({ | |
apiVersion: '2006-03-01', | |
accessKeyId: process.env.AWS_S3_BROWSER_KEY_ID, | |
secretAccessKey: process.env.AWS_S3_BROWSER_SECRET, | |
region: 'us-east-1', | |
params: { Bucket: 'your-default-bucket' } | |
}); | |
/** | |
* A better wrapper for browser S3 uploads | |
* | |
* @see https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property | |
* @param {File} file - the File object from the input selector | |
* @param {string} filePath - where you want the file to be saved in the bucket | |
* @param {function} onCompletion - to be executed on successful upload and delivers the full url location | |
* @param {function} onProgress - to be executed at each upload progress point and delivers completion percentage | |
* @param {function} onError - to be executed if there is an upload error | |
*/ | |
export function s3Upload(file, filePath, onCompletion, onProgress, onError) { | |
s3.upload({ | |
Key: filePath, | |
Body: file, | |
// ACL: 'public-read' /* Use this only if you want the file to be publicly accessable */ | |
}, function(error, data) { | |
if(error) { | |
if(typeof onError === "function") { | |
onError(error.message); | |
} | |
return; | |
} | |
if(typeof onCompletion === "function") { | |
onCompletion(data.Location); | |
} | |
}).on("httpUploadProgress", function (progress) { | |
if(typeof onProgress !== "function") { | |
return; | |
} | |
const uploadProgress = parseInt(progress.loaded / progress.total * 100); | |
onProgress(uploadProgress); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment