当前是multer的新手,所以这是我的问题:
尝试将jpg图片发布到mysql时,我一直得到MulterError: Unexpected field
作为输出。谁能看到我的代码中的错误?当前,当我上传一张大于1MB的图片时,我正在尝试生成一条错误消息。
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);
})
}
}
})
答案 0 :(得分:1)
尝试使用fileSize:
限制:{ fileSize:2 * 1024 * 1024 // 2 MB}