无论我做什么,Multer 都不会填充 req.file

时间:2021-05-23 08:06:30

标签: javascript node.js file-upload multer

我确实尝试了所有可能的解决方案,但没有一个有效,有趣的是我确实可以访问 req.body 但无法访问 req.file。如果有人有任何想法,请分享,谢谢。

形式:

<form action="/books" method="POST" enctype="multipart/form-data">
    <label for="cover">Cover</label>
    <input type="file" id="cover" name="cover">
    <button type="submit">Create</button>
</form>

路由处理程序:

const imageMimeTypes = ['image/jpeg','image/jpg','image/png', 'image/gif']
const upload = multer({
    dest: uploadPath,
    fileFilter(req, file, callback){
        if(imageMimeTypes.includes(file.mimetype)){
            return callback(null, true)
        }
        callback(new Error('the mimetype of the image is not valid'), null)
    }
})
router.post('/', upload.single('cover'), async (req, res) => {
    const book = new Book({
        title: req.body.title,
        author: req.body.author,
        publishDate: new Date(req.body.publishDate),
        pageCount: req.body.pageCount,
        description: req.body.description,
        coverImageName: req.file.filename
    })
    try {
      await book.save();
      res.redirect('/books')
    } catch (error) {
      renderNewPage(res, book, true)
  }
})

0 个答案:

没有答案