如何在 Postman 中上传图像文件并使用 Express 和 Multer 回显相同的图像

How to upload image files in Postman and echo back the same image using Express and Multer

我正在尝试使用邮递员上传产品并在我提交的任何时候上传;它发回带有图像 undefined 的所有数据,如屏幕截图所示:

我的控制器文件:

const gameRepository = require("../routes/repository")

exports.createGame = async (req, res, next) => {
    try {
        const PORT = 8000;
        const hostname = req.hostname;
        const url = req.protocol + '://' + hostname + ':' + PORT + req.path;

        const payload = ({
            name: 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.path
        });          
        
        let eachGame = await gameRepository.createGame({
            ...payload
        });

        console.log(req.body)

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

repository.js:

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.create(payload);
    return newGame;
}

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

Multer.js:


const multer = require("multer");
const path = require("path");

// 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 + new Date().toISOString() + '.' + extension);
    }
});

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

我不确定我哪里出错了,这就是为什么我需要外在的眼睛来帮助定位故障的原因。

我感觉我需要使用 body-parser 或正确导航到图像文件夹,或多部分表格,我不确定。

经过多次尝试和失败后,我终于弄明白了。 事实证明它存在兼容性问题,具体取决于您的 OS.

我使用 windows 10,这为我解决了问题

这是我的工作代码:

multer.js


const multer = require("multer");
const path = require("path");


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

// Image Upload
const storage = multer.diskStorage({
    destination: (req, file, cb ) => {
      cb(null, ('storage/imgs/'));
    },
    filename: (req, file, cb) => {
        const extension = MIME_TYPES[file.mimetype];
    
    // I added the colons in the date of my image with the hyphen 
        cb(null, `${new Date().toISOString().replace(/:/g,'-')}.${extension}`);
    }
});

module.exports = multer({
    storage: storage
})

在我的controller.js


const gameRepository = require("../routes/repository");

exports.createGame = async (req, res, next) => {
  try {
    const payload = {
      name: 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: req.file.filename,
    };

    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,
    });
  }
};

exports.getGames = async (req, res) => {
  try {
    let games = await gameRepository.games();
    res.status(200).json({
      status: true,
      data: games,
    });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      error: err,
      status: false,
    });
  }
};

exports.getGameById = async (req, res) => {
  try {
    let id = req.params.id;
    let gameDetails = await gameRepository.gameById(id);
    req.req.status(200).json({
      status: true,
      data: gameDetails,
    });
  } catch (err) {
    res.status(500).json({
      status: false,
      error: err,
    });
  }
};

exports.removeGame = async (req, res) => {
  try {
    let id = req.params.id;
    let gameDetails = await gameRepository.removeGame(id);
    res.status(200).json({
      status: true,
      data: gameDetails,
    });
  } catch (err) {
    res.status(500).json({
      status: false,
      data: err,
    });
  }
};

:

Postman output

感谢这个伟大的社区。