Использовать Multer в экспресс-маршруте? (Используя MEANJS)
Я использую Multer для загрузки изображений в Express 4. Однако во всех примерах Multer определен в файле Express как Middleware. Я хотел бы на самом деле определить некоторые из поведений Multer в самой маршрутизации моего приложения. Это возможно? Конечный результат, который мне нужен, состоит в том, чтобы моя функция маршрута распознала, когда загрузка завершена, прежде чем она отправит ответ сервера в браузер, поэтому изображение может быть отображено пользователю (сейчас я получаю только частичное изображение, потому что файл еще не закончил загрузку).
ТЕКУЩИЙ, РАБОЧИЙ КОД
express.js
// Require Multer as module dependency.
var multer = require('multer');
// 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) {
if(file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') {
return false;
}
}
}));
server_routes.js
app.route('/users/image').post(server_controller_file.imageUpload);
server_controller_file.js
exports.imageUpload = function(req, res) {
// Check to make sure req.files contains a file, mimetypes match, etc., then send appropriate server response.
};
В идеале мой server_controller_file.js должен содержать некоторые проверки, чтобы убедиться, что файл завершил загрузку, например (примечание: это гипотетический / желательный, а не фактический рабочий код)...
var multer = require('multer');
exports.imageUpload = function(req, res) {
multer({
onFileUploadComplete: function(file) {
res.send();
}
});
}
Опять же, прямо сейчас асинхронная природа узла заставляет браузер думать, что загрузка завершена, как только он получает успешный ответ, поэтому, когда я обновляю URL для отображения изображения, он отображается только частично. Спасибо за помощь!
3 ответа
ОК, я только что закончил писать необработанные данные. Если вы установите inMemory
в true
, он отправляет необработанные данные в req.files.file.buffer. Вот последнее, рабочее решение:
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.');
};
На самом деле вы можете делать то, что вы хотите с другим методом:
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);
Я нахожу пример для busboy:
exports.upload = function (req, res, next) {
req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
// ....
});
req.pipe(req.busboy);
};
Малтер тоже трубочист
req.pipe(busboy);
https://github.com/expressjs/multer/blob/master/index.js#206