Last active
April 25, 2017 19:41
-
-
Save mulatinho/28e01801d92d3d0000e7935d854b9fd8 to your computer and use it in GitHub Desktop.
uploading to amazon S3 without AWS-SDK or any other module but native
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
/* Upload to Amazon S3 without AWS-SDK or other modules | |
* Alexandre Mulatinho <alex at mulatinho.net> 2016 | |
* | |
* You will need to change: | |
* - YOUR_FILENAME_HERE | |
* - YOUR_BUCKET_HERE | |
* - AWS_SECRET_KEY_HERE | |
* - AWS_ACCESS_KEY_HERE */ | |
var https = require("https"); | |
var fs = require("fs"); | |
var crypto = require("crypto"); | |
var buffer = require("buffer"); | |
var dataNow = new Date().toUTCString().replace('GMT', '+0000') | |
var filename = "YOUR_FILENAME_HERE." | |
var remoteFile = "/YOUR_BUCKET_HERE/" + filename; | |
var szFilename = fs.statSync(filename).size | |
var contentFile = fs.readFileSync(filename); | |
var md5sum = crypto.createHash('md5').update(contentFile).digest(); | |
var base64_md5 = new Buffer(md5sum).toString('base64'); | |
var stringToSign="PUT\n" + base64_md5 + "\napplication/octet-stream\n" + dataNow + "\nx-amz-acl:public-read\n" + remoteFile; | |
var sha1sum = crypto.createHmac('sha1', 'AWS_SECRET_KEY_HERE').update(stringToSign).digest(); | |
var base64 = new Buffer(sha1sum).toString('base64'); | |
var authorization = "AWS AWS_ACCESS_KEY_HERE:" + base64; | |
var options = { | |
"method": "PUT", | |
"hostname": "s3-us-west-2.amazonaws.com", | |
"port": "443", | |
"path": remoteFile, | |
"headers": { | |
"Host": "s3-us-west-2.amazonaws.com", | |
"Date": dataNow, | |
"Accept": "*/*", | |
"x-amz-acl": "public-read", | |
"Content-Length": szFilename, | |
"Content-Type": "application/octet-stream", | |
"Content-MD5": base64_md5, | |
"Authorization": authorization, | |
"Expect": "100-continue" | |
} | |
}; | |
var req = https.request(options, function (res) { | |
var buffer = ''; | |
res.setEncoding('utf8'); | |
res.on("data", function (chunk) { | |
buffer += chunk; | |
}); | |
res.on("end", function () { | |
console.log(res.statusCode, res.statusMessage); | |
console.log(res.headers) | |
console.log('https://' + options.hostname + options.path) | |
console.log(buffer); | |
}); | |
}); | |
req.write(contentFile); | |
req.end(); | |
req.on('error', (e) => { | |
console.error(e); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment