-
-
Save ff6347/6dc8151acf449dd5bdb1a580f24086bd to your computer and use it in GitHub Desktop.
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
import aws from 'aws-sdk-promise'; | |
import url from 'url'; | |
import https from 'https'; | |
import fs from 'mz/fs'; | |
import _ from 'lodash'; | |
import path from 'path'; | |
import crypto from 'crypto'; | |
(async function() { | |
// Compute hash | |
var filename = path.join(__dirname, 'test.tar.gz'); | |
var hash = await new Promise((accept, reject) => { | |
var md5 = crypto.createHash('md5'); | |
var stream = fs.createReadStream(filename); | |
stream.on('data', d => md5.update(d)); | |
stream.on('end', () => accept(md5.digest('base64'))); | |
stream.on('error', reject); | |
}); | |
console.log("hash: " + hash); | |
// Generated signed url | |
var s3 = new aws.S3(); | |
var signedURL = await new Promise((accept, reject) => { | |
s3.getSignedUrl('putObject', { | |
Bucket: 'test-bucket-for-any-garbage', | |
Key: 'jonasfj-upload-test/test.tar', | |
ContentType: 'application/x-tar', | |
Expires: 15 * 60, // URL expiration | |
ContentMD5: hash, | |
Metadata: { | |
"content-sha256": "Hello World2" | |
} | |
}, (err, url) => err ? reject(err) : accept(url)); | |
}); | |
console.log("Signed URL: " + signedURL); | |
// Open file | |
var stat = await fs.stat(filename); | |
var stream = fs.createReadStream(filename); | |
// Upload | |
var urlOpts = url.parse(signedURL); | |
var req = https.request({ | |
method: 'PUT', | |
host: urlOpts.host, | |
path: urlOpts.path, | |
headers: { | |
'content-type': 'application/x-tar', | |
'content-length': stat.size, | |
'content-encoding': 'gzip', | |
'cache-control': 'public, no-transform', | |
'content-md5': hash | |
} | |
}); | |
// Pipe stream | |
stream.pipe(req); | |
var res = await new Promise((accept, reject) => { | |
req.on('response', accept); | |
req.on('error', reject); | |
req.setTimeout(5 * 60 * 1000, reject); | |
}); | |
// Print status code | |
console.log("Response Code: " + res.statusCode); | |
// Discard response text | |
res.resume(); | |
})().catch(err => console.log(err.stack)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment