I\'m using Multer to upload images in Express 4. However, the examples all show Multer being defined in the express file as Middleware. I\'d like to actually define some of
OK, I actually just ended up writing the raw data. If you set inMemory to true, it sends the raw data to req.files.file.buffer. Here's the final, working solution:
express.js
// Using Multer for file uploads.
app.use(multer({
dest: './public/profile/img/',
limits: {
fieldNameSize: 50,
files: 1,
fields: 5,
fileSize: 1024 * 1024
},
rename: function(fieldname, filename) {
return filename;
},
onFileUploadStart: function(file) {
console.log('Starting file upload process.');
if(file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') {
return false;
}
},
inMemory: true //This is important. It's what populates the buffer.
}));
server_controller_file.js
exports.imageUpload = function(req, res) {
var file = req.files.file,
path = './public/profile/img/';
// Logic for handling missing file, wrong mimetype, no buffer, etc.
var buffer = file.buffer, //Note: buffer only populates if you set inMemory: true.
fileName = file.name;
var stream = fs.createWriteStream(path + fileName);
stream.write(buffer);
stream.on('error', function(err) {
console.log('Could not write file to memory.');
res.status(400).send({
message: 'Problem saving the file. Please try again.'
});
});
stream.on('finish', function() {
console.log('File saved successfully.');
var data = {
message: 'File saved successfully.'
};
res.jsonp(data);
});
stream.end();
console.log('Stream ended.');
};