如何解决expressjs / multer中文件类型验证中的MulterError:Unexpected字段?

时间:2019-03-26 19:20:27

标签: html node.js multer

我正在尝试在expressjs / multer中进行文件类型验证,因为从此下面的代码中,我无法在本地上传文件,并且出现以下错误。

MulterError:意外字段     在wrappedFileFilter(C:\ Users \ Sarvesh \ node_modules \ multer \ index.js:40:19)等...

const express = require('express');
const multer = require('multer');
const fileType = require('file-type');

const app = new express();
const accepted_extensions = ['jpg', 'png', 'gif'];
const upload = multer({
    limits: { 
        fileSize: 5 * 1024 * 1024,  // 5 MB upload limit
        files: 1                    // 1 file
    },
    fileFilter: (req, file, cb) => {
        // if the file extension is in our accepted list
        if (accepted_extensions.some(ext => file.originalname.endsWith("." + ext))) {
            return cb(null, true);
        }

        // otherwise, return error
        return cb(new Error('Only ' + accepted_extensions.join(", ") + ' files are allowed!'));
    }
});

app.get('/',function(req,res){
      res.sendFile(__dirname + "/index.html");
});


/**
 * Middleware for validating file format
 */
function validate_format(req, res, next) {
    // For MemoryStorage, validate the format using `req.file.buffer`
    // For DiskStorage, validate the format using `fs.readFile(req.file.path)` from Node.js File System Module
    let mime = fileType(req.file.buffer);

    // if can't be determined or format not accepted
    if(!mime || !accepted_extensions.includes(mime.ext))
        return next(new Error('The uploaded file is not in ' + accepted_extensions.join(", ") + ' format!'));

    next();
}

app.post("/", 
    // First middleware, validate number of files (one file) / size (5MB) / extension ('jpg', 'png', 'gif')
    upload.single("file_field_name"), 

    // Second middleware, validate file format ('jpg', 'png', 'gif')
    validate_format,

    function(req, res, next) {
        // Passed validations, do something with the file (`req.file`)
        // ...


        res.send("file uploaded");
    }
);

app.listen(3000, () => {
    console.log("Express listening on port 3000");
});

0 个答案:

没有答案