【问题标题】:Multer TypeError: Cannot read property ‘filename’ of undefinedMulter TypeError:无法读取未定义的属性“文件名”
【发布时间】:2021-03-29 06:38:13
【问题描述】:

我这几天一直在与这个错误作斗争,我认为最好寻求帮助。

我将在下面列出文件及其代码。

multer.js 文件

const multer = require("multer");
const path = require("path");
const { fileURLToPath } = require("url");

// checking for file type
const MIME_TYPES = {
    'imgs/jpg': 'jpg',
    'imgs/jpeg': 'jpeg',
    'imgs/png': 'png'
}

// Image Upload
const storage = multer.diskStorage({
    destination: (req, file, cb ) => {
      cb(null, path.join('../imgs/'));
    },
    filename: (req, file, cb) => {
        const name = file.originalname.split('').join(__);
        const extension = MIME_TYPES[file.mimetype];
        cb(null, name + Date.now() + '.' + extension);
    }
});

module.exports = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 6
    },
})

repository.js 文件 在这里,我从 gameModel 导入了我的架构。

const Game = require("../models/gameModel");

exports.games = async () => {
    const games = await Game.find();
    return games;
}

exports.gameById = async id => {
    const game = await Game.findById(id);
    return game;
}

exports.createGame = async payload => {
    const newGame = await Game.createGame(payload);
    return newGame;
}

exports.removeGame = async id => {
    const game = await Game.findById(id);
    return game;
}

controller.js 我开始在这里感到困惑,因为我尝试了在互联网上看到的不同代码选项

const gameRepository = require("../routes/repository")
const Game = require('../models/gameModel')

exports.createGame = async (req, res, next) => {
    
    try {
        // req.body.game = JSON.parse(req.body.game)
        const hostname = req.hostname;
     const url = req.protocol + '://' + hostname + req.file.filename;

        const payload = new Game({
            title: req.body.name,
            price: req.body.price,
            category: req.body.category,
            gameIsNew: req.body.gameIsNew,
            topPrice: req.body.topPrice,
            isVerOrient: req.body.IsVerOrient,
            description: req.body.description,
            image: url + 'imgs/' + req.file.filename       //  The error is from here
        });          

        let eachGame = await gameRepository.createGame({
            ...payload
        });

        res.status(200).json({
            status: true,
            data: eachGame,
        })

    } catch (err) {
        console.log(err)
        res.status(500).json({
            error: err,
            status: false,
        })
    }
}

gameRouter.js

const express = require('express');
const router = express.Router();
const gameController = require("../controller/game.controller");
const multerInstance = require('./multer')


router.post("/game", multerInstance.single('image'),
gameController.createGame
)

router.get("/game", gameController.getGames);

router.get("/game/:id", gameController.getGameById);

router.delete("/game/:id", gameController.removeGame);


module.exports = router

提前感谢您的帮助。

【问题讨论】:

  • 错误出现在哪一行?
  • 感谢您与我们联系!错误在 controller.js 文件图像中:req.file.filename
  • 感谢您的宝贵时间。我会给你反馈我得到的结果。
  • 我使用您建议的方法解决了这个问题。非常感谢您的帮助。原来是req.body.filename。
  • 涂料。一个upvote会很好:)

标签: javascript node.js postman multer mern


【解决方案1】:

req.file.filename 未定义...更具体地说,req.file 可能未定义...但是,我有预感 req.body.filereq.body.file.filename 或者可能...req.body.filename 已定义。你可以随时console.log(req.file) 来查看它的内容,前提是你从 cmd 窗口运行它。

【讨论】:

    猜你喜欢
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2018-06-03
    • 2021-02-15
    • 2021-11-13
    • 2022-01-14
    相关资源
    最近更新 更多