Created
June 25, 2019 16:02
-
-
Save nishant8BITS/0fbfb259aaff9f684a4e584b59ea13b6 to your computer and use it in GitHub Desktop.
Upload file to Amazon S3 using signed URL in Node.js
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
var AWS = require('aws-sdk'); | |
var fs = require('fs'); | |
var http = require('https'); | |
var url = require('url'); | |
var request = require('request'); | |
var s3 = new AWS.S3({ | |
accessKeyId: 'KEY', | |
secretAccessKey: 'SECRET', | |
region: 'eu-west-1' | |
}); | |
//request.debug = true; | |
var params = { | |
Bucket: 'bucket', | |
Key: 'test-upload-file', | |
Expires: 14 * 24 * 3600 | |
}; | |
var signedUrlPut = s3.getSignedUrl('putObject', params); | |
//console.log('curl -v -T components_map.json "' + signedUrlPut + '"'); | |
var signedUrlRead = s3.getSignedUrl('getObject', params); | |
console.log('READ', signedUrlRead); | |
var remoteUrl = 'http://example.com'; | |
var sourceRequest = request.get(remoteUrl); | |
sourceRequest.on('response', onResponse); | |
function onResponse(res) { | |
var contentLength = res.headers['content-length']; | |
console.log(contentLength); | |
console.log('On response'); | |
res.pipe(getUploadStream(signedUrlPut, contentLength)); | |
} | |
function getUploadStream(repoteUrl, contentLength) { | |
var opts = url.parse(repoteUrl); | |
opts.method = 'PUT'; | |
opts.headers = { | |
'Content-Length': contentLength | |
}; | |
var req = http.request(opts, onRequest); | |
function onRequest(res) { | |
console.log('STATUS: ' + res.statusCode); | |
console.log('HEADERS: ' + JSON.stringify(res.headers)); | |
res.setEncoding('utf8'); | |
res.on('data', function(chunk) { | |
console.log('BODY: ' + chunk); | |
}); | |
res.on('end', function() { | |
console.log('No more data in response.') | |
}); | |
} | |
return req; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment