简体   繁体   中英

Error In Multer When Trying To Upload A Image

Currently new to multer, so here's my problem: I kept getting the MulterError: Unexpected field as the output when i try to POST the jpg image into mysql. Can anyone see whats the bug in my code? Currently im trying to make a error message when an image of more than 1MB is uploaded.

var multer = require('multer');
var path = require('path');
var storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, './uploads');
    },
    filename: function (req, file, callback) {
        callback(null, file.fieldname + '-' + new Date().toISOString() + '-' + path.extname(file.originalname));
    }
});
var upload = multer({storage: storage});

// Endpoint 13 (EXTRA FEATURE 1)
const fileFilter = (req, file, callback) => {
    if(file.mimetype === 'image/jpg') {
        callback(null,true);
    }
    callback(null,false);
}

var uploadFromDesktop = multer({
    storage:storage,
    limits: {
        fieldSize: 1024 * 1024
    },
    fileFilter: fileFilter
});

app.post("/upload/", upload.single('productImage'), (req, res, next) => {
    uploadFromDesktop(req,res),(error) => {
        console.log(error);
        if (error) {
            if (error.code === 'LIMIT_FILE_SIZE') {
            } else {
                res.status(500).send({ 'status': status, 'error':error})
                }
            } else {
                var temp = req.file.path;
                var file = uploadDir + req.file.originalname;
                var source = fs.createReadStream(temp);
                var destination = fs.createWriteStream(file);
                source.pipe(destination);
                fs.unlink(temp);
                source.on('end',function () {
                    var result = {
                        'status': 'success',
                        'file': file
                    }
                    fs.chmod(file,0777);
                    res.send(result);
                })
                source.on('error', function (error) {
                    var result = {
                        'status': 'Fail',
                        'error': error
                    };
                    res.send(result);
                })
            }
        }
    })

Try with fileSize:

limits: { fileSize: 2 * 1024 * 1024 // 2 MB}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM