在 Express Route 中使用 Multer? (使用 MEANJS)

Use Multer in Express Route? (Using MEANJS)

我正在使用 Multer 在 Express 4 中上传图像。但是,所有示例都显示 Multer 在 express 文件中被定义为中间件。我想在我的应用程序路由本身中实际定义一些 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 会包含一些检查以确保文件已完成上传,例如(注意:这是 hypothetical/desirable,不是实际工作代码)...

var multer = require('multer');
exports.imageUpload = function(req, res) {
    multer({
        onFileUploadComplete: function(file) {
            res.send();
        }
    });
}

同样,现在节点的异步特性导致浏览器在收到成功响应后立即认为上传已完成,所以当我更新 url 以显示图像时,它只部分显示。感谢您的帮助!

我找到了一个服务生的例子:

exports.upload = function (req, res, next) {
   req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
       // ....
   });

   req.pipe(req.busboy);
};

multer 也是一个服务员:

 req.pipe(busboy);

https://github.com/expressjs/multer/blob/master/index.js#206

好的,实际上我刚刚写完了原始数据。如果将 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);