var mongoose = require(‘mongoose’); var Grid = require(‘gridfs-stream’); var async = require(‘async’); var gfs = Grid(mongoose.connection.db, mongoose.mongo); var GridFile = require(‘…/…/models/gridfs’).GridFile;
var put_save = function(req, res) { var fnames = util.isArray(req.files.fname) ? req.files.fname : [req.files.fname]; async.map(fnames, process_file, function(err, results) { res.json({ 'err’: err, 'results’: results }) })
function process_file(fname, callback) {
var gfs_options = {
filename: fname.name,
mode: 'w',
content_type: fname.type,
metadata: {
'client': req.user.client.id,
'user': req.user.id
}
};
var writestream = gfs.createWriteStream(gfs_options);
fs.createReadStream(fname.path).pipe(writestream);
writestream.on('close', function(file) {
fs.unlink(fname.path, function(err) {
if (err) {
return callback(err, null);
};
callback(null, file)
});
});
}
}