Javascript 在 Express Route 中使用 Multer?(使用 MEANJS)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27785896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Multer in Express Route? (Using MEANJS)
提问by aikorei
I'm using Multerto 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 the Multer behaviors in my app routing itself. Is this possible? The end result that I need is for my route function to recognize when the upload is finished before it sends the server response to the browser, so an image can be displayed to the user (right now I'm only getting a partial image displayed because the file hasn't finished uploading yet).
我正在使用Multer在 Express 4 中上传图像。但是,这些示例都显示 Multer 在 express 文件中被定义为中间件。我想在我的应用程序路由本身中实际定义一些 Multer 行为。这可能吗?我需要的最终结果是让我的路由功能在将服务器响应发送到浏览器之前识别上传何时完成,因此可以向用户显示图像(现在我只显示部分图像,因为文件尚未完成上传)。
CURRENT, WORKING CODE
当前的工作代码
express.js
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
server_routes.js
app.route('/users/image').post(server_controller_file.imageUpload);
server_controller_file.js
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.
};
Ideally, my server_controller_file.js would contain some checks to make sure the file finished uploading, e.g. (note: this is hypothetical/desirable, not actual working code)...
理想情况下,我的 server_controller_file.js 将包含一些检查以确保文件完成上传,例如(注意:这是假设的/可取的,而不是实际的工作代码)...
var multer = require('multer');
exports.imageUpload = function(req, res) {
multer({
onFileUploadComplete: function(file) {
res.send();
}
});
}
Again, right now the async nature of node is causing the browser to think the upload is complete as soon as it receives a successful response, so when I update the url to display the image, it only partially displays. Thanks for the help!
同样,现在节点的异步性质导致浏览器在收到成功响应后认为上传已完成,因此当我更新 url 以显示图像时,它仅部分显示。谢谢您的帮助!
采纳答案by aikorei
OK, I actually just ended up writing the raw data. If you set inMemoryto true, it sends the raw data to req.files.file.buffer. Here's the final, working solution:
好吧,我实际上只是写了原始数据。如果设置inMemory为true,它将原始数据发送到 req.files.file.buffer。这是最终的工作解决方案:
express.js
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
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.');
};
回答by Aymen Mouelhi
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);
回答by Ryan Yiada
I find an example for busboy:
我找到了一个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:
multer 也是管一个busboy:
req.pipe(busboy);
https://github.com/expressjs/multer/blob/master/index.js#206
https://github.com/expressjs/multer/blob/master/index.js#206

