我正在尝试使用 multer 在我的 REST API 中上传 3 个文件,但只有第一个文件被上传。我已经配置正确了,但是为什么我会遇到这个错误。请帮忙...
//route.js
router.patch(
protect,
restrictToRole('admin'),
uploadtourPhotos,
resizeTourPhotos,
updateTour,
)
//controller.js
const storage = multer.memoryStorage();
const multerFileFilter = (req, file, cb) => {
if (file.mimetype.startsWith('image')) {
cb(null, true);
} else {
cb(new AppError(400, `Uploaded file is not an image.`), false);
}
};
const upload = multer({
storage: storage,
fileFilter: multerFileFilter,
});
exports.uploadtourPhotos = upload.fields([
{ name: 'coverImage', maxCount: 1 },
{ name: 'image', maxCount: 2 },
]);
exports.resizeTourPhotos = handleAsync(async (req, res, next) => {
console.log(req.files);
console.log(req.body);
next();
});
log:
💻 App running on PORT: 8000 🏃
✔ connected to database ⛁
[Object: null prototype] {
coverImage: [
{
fieldname: 'coverImage',
originalname: 'garbage collection js.png',
encoding: '7bit',
mimetype: 'image/png',
buffer: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 40 00 00 03 48 08 06 00 00 00 9f 67 23 6d 00 00 00 09 70 48 59 73 00 00 0e c4 00 00 0e c4 01 ... 186726 more bytes>,
size: 186776
}
]
}
[Object: null prototype] { image: [ '', '' ] }
做了一些更改,现在工作正常。我认为这是由于 bodyParser.json() 或在 router.patch 中使用 export. 导致的
const express = require('express');
const router = express.Router();
const multer = require('multer');
const bodyParser = require('body-parser');
const handleAsync = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
const protect = (req, res, next) => {
console.log('Protect middleware');
next();
};
const restrictToRole = (role) => (req, res, next) => {
console.log(`Restrict to ${role} middleware`);
next();
};
const storage = multer.memoryStorage();
const multerFileFilter = (req, file, cb) => {
if (file.mimetype.startsWith('image')) {
cb(null, true);
} else {
cb(new Error('Uploaded file is not an image.'), false);
}
};
const upload = multer({
storage: storage,
fileFilter: multerFileFilter,
});
router.use(bodyParser.json());
exports.uploadtourPhotos = upload.fields([
{ name: 'coverImage', maxCount: 1 },
{ name: 'image', maxCount: 2 },
]);
exports.resizeTourPhotos = handleAsync(async (req, res, next) => {
console.log(req.files);
console.log(req.body);
next();
});
router.patch(
'/',
protect,
restrictToRole('admin'),
exports.uploadtourPhotos,
exports.resizeTourPhotos,
);
module.exports = router;