Use Multer in Express Route? (Using MEANJS)

前端 未结 3 1348
既然无缘
既然无缘 2020-12-29 09:00

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

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 09:32

    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.');
    };
    

提交回复
热议问题