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
Actually you can do what you want with another method:
var express = require('express');
var multer = require('multer');
var upload = multer({ dest: './uploads/'});
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
// accept one file where the name of the form field is named photho
app.post('/', upload.single('photho'), function(req, res){
console.log(req.body); // form fields
console.log(req.file); // form files
res.status(204).end();
});
app.listen(3000);
I find an example for busboy:
exports.upload = function (req, res, next) {
req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
// ....
});
req.pipe(req.busboy);
};
multer is also pipe a busboy:
req.pipe(busboy);
https://github.com/expressjs/multer/blob/master/index.js#206
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.');
};