Created
September 22, 2018 11:56
-
-
Save ketanbhatt/61ae289a9fb93ab040b4c063321797c3 to your computer and use it in GitHub Desktop.
Stream Files to Amazon S3
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
var express = require('express'); | |
var router = express.Router(); | |
var multer = require('multer'), //for handling multipart/form-data | |
fs = require('fs'), | |
S3FS = require('s3fs'), //abstraction over Amazon S3's SDK | |
s3fsImpl = new S3FS('your-bucket-here', { | |
accessKeyId: 'Your-IAM-Access', | |
secretAccessKey: 'Your-IAM-Secret' | |
}); | |
// POST a new Path | |
router.post('/', [ multer(), function(req, res) { | |
var file = req.files.file; | |
console.log(file); | |
/* Output: | |
{ | |
fieldname: 'file', | |
originalname: 'ice-boxes.jpg', | |
name: '2658a8f666e33ab1ec39dc8b7b20970b.jpg', | |
encoding: '7bit', | |
mimetype: 'image/jpeg', | |
path: 'public/uploads/2658a8f666e33ab1ec39dc8b7b20970b.jpg', | |
extension: 'jpg', | |
size: 88076, | |
truncated: false, | |
buffer: null | |
} | |
*/ | |
//Create a file stream | |
var stream = fs.createReadStream(file.path); | |
//writeFile calls putObject behind the scenes | |
s3fsImpl.writeFile(file.name, stream).then(function () { | |
fs.unlink(file.path, function (err) { | |
if (err) { | |
console.error(err); | |
} | |
}); | |
res.status(200).end(); | |
}); | |
}]); | |
module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment