Created
July 8, 2016 00:56
-
-
Save DingGGu/45acfb09f06d422326b98c540d1b3fdc to your computer and use it in GitHub Desktop.
Multer multiple upload S3 with Resizing Images
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 config = require('../config'); | |
var async = require('async'); | |
var gm = require('gm'); | |
var mime = require('mime'); | |
var stream = require('stream'); | |
var aws = require('aws-sdk'); | |
var s3 = new aws.S3(config.aws); | |
function AvatarUpload() { | |
} | |
function passStream(req, file, cb) { | |
file.stream.once('data', function (firstChunk) { | |
var outStream = new stream.PassThrough(); | |
var outStream2 = new stream.PassThrough(); | |
outStream.write(firstChunk); | |
file.stream.pipe(outStream); | |
outStream2.write(firstChunk); | |
file.stream.pipe(outStream2); | |
cb(null, outStream, outStream2) | |
}) | |
} | |
AvatarUpload.prototype._handleFile = function _handleFile(req, file, cb) { | |
var timestamp = Date.now().toString(); | |
var nick = req.member.ss_mb_id; | |
file.endpoint = nick + "_" + timestamp + '.' + mime.extension(file.mimetype); | |
var fileName = nick.substring(0, 2) + '/' + file.endpoint; | |
passStream(req, file, function (err, outStream, outStream2) { | |
async.parallel([ | |
function (callback) { | |
var imageSize = 500; | |
gm(outStream) | |
.resize(imageSize, imageSize, '^') | |
.autoOrient() | |
.noProfile() | |
.gravity('Center') | |
.crop(imageSize, imageSize) | |
.stream(function (err, stdout, stderr) { | |
if (err) return callback(err); | |
var upload = s3.upload({ | |
Bucket: '{{ YOUR BUCKET }}', | |
Key: '{{ YOUR KEY }}' + fileName, | |
ACL: 'public-read', | |
Body: stdout, | |
ContentType: file.mimetype | |
}); | |
upload.send(function (err, results) { | |
if (err) return callback(err); | |
callback(null, results); | |
}); | |
}); | |
}, | |
function (callback) { | |
var imageSize = 50; | |
gm(outStream2) | |
.resize(imageSize, imageSize, '^') | |
.autoOrient() | |
.noProfile() | |
.gravity('Center') | |
.crop(imageSize, imageSize) | |
.stream(function (err, stdout, stderr) { | |
if (err) return callback(err); | |
var upload2 = s3.upload({ | |
Bucket: '{{ YOUR BUCKET }}', | |
Key: '{{ YOUR KEY }}' + fileName, | |
ACL: 'public-read', | |
Body: stdout, | |
ContentType: file.mimetype | |
}); | |
upload2.send(function (err, results) { | |
if (err) return callback(err); | |
callback(null, results); | |
}) | |
}); | |
} | |
], function (err, results) { | |
if (err) cb(err); | |
else { | |
cb(null, results); | |
} | |
}); | |
}) | |
}; | |
module.exports = function () { | |
return new AvatarUpload(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment