Created
June 13, 2018 21:44
-
-
Save mrcnc/0c097a2d6f490767ced83091dc8aed25 to your computer and use it in GitHub Desktop.
simple s3 uploader
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Simple Uploader</title> | |
<meta charset="utf-8"> | |
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.243.1.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-md5/2.10.0/js/md5.min.js"></script> | |
</head> | |
<body> | |
<form> | |
<input type="file" id="file-chooser" multiple /> | |
<button id="upload-button">Upload to S3</button> | |
</form> | |
<div id="results"></div> | |
<script type="text/javascript"> | |
var accessKeyId = ''; | |
var secretAccessKey = ''; | |
var bucket = new AWS.S3({ | |
accessKeyId, | |
secretAccessKey, | |
params: { | |
Bucket: '', | |
Region: '', | |
} | |
}); | |
var fileChooser = document.getElementById('file-chooser'); | |
var button = document.getElementById('upload-button'); | |
var results = document.getElementById('results'); | |
button.addEventListener('click', function () { | |
// todo: handle multiple files | |
var file = fileChooser.files[0]; | |
if (file) { | |
console.log(file); | |
results.innerHTML = ''; | |
// choose key wisely: https://docs.aws.amazon.com/AmazonS3/latest/dev/request-rate-perf-considerations.html#introduce-randomness-hash | |
var key = md5(file.body).substring(0, 4) + '-' + new Date().toISOString().split('T')[0] | |
// + '/' + userId | |
+ '/' + file.name; | |
var params = { | |
Key: key, | |
ContentType: file.type, | |
Body: file, | |
//Tagging: "key1=value1&key2=value2" | |
}; | |
// if file size over 100 MB | |
if (file.size > 100000000) { | |
console.log('using multipart') | |
// use multipart upload: https://docs.aws.amazon.com/AmazonS3/latest/dev/uploadobjusingmpu.html | |
bucket.upload(params, function (err, data) { | |
results.innerHTML = err ? 'ERROR!' : 'UPLOADED!'; | |
}).on('httpUploadProgress', function (evt) { | |
console.log('Progress:', evt.loaded, '/', evt.total, evt.loaded / evt.total); | |
}).send(function (err, data) { | |
results.innerHTML = err ? 'ERROR!' : `UPLOADED to ${data.Location}`; | |
}); | |
} else { | |
// get pre-signed url for put: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getSignedUrl-property | |
bucket.putObject(params, function (err, data) { | |
results.innerHTML = err ? 'ERROR!' : 'UPLOADED!'; | |
}); | |
} | |
} else { | |
results.innerHTML = 'Nothing to upload.'; | |
} | |
}, false); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment