14

我正在使用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 将包含一些检查以确保文件完成上传,例如(注意:这是假设/理想的,不是实际的工作代码)...

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

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

4

3 回答 3

18

实际上你可以用另一种方法做你想做的事:

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);

于 2015-03-19T13:34:50.603 回答
7

好的,我实际上刚刚写了原始数据。如果设置inMemorytrue,它将原始数据发送到 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.');
};
于 2015-01-06T21:37:44.940 回答
2

我找到了一个 busboy 的例子:

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

于 2015-01-06T01:09:57.547 回答