【问题标题】:How to upload image files in Postman and echo back the same image using Express and Multer如何在 Postman 中上传图像文件并使用 Express 和 Multer 回显相同的图像
【发布时间】:2021-03-31 11:59:19
【问题描述】:

我正在尝试使用邮递员上传产品,并且我随时提交;它发回带有图像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 或者正确导航到图像文件夹,或者多部分表单,我不确定。

【问题讨论】:

  • 您提到了 multer 用于文件上传,但您的代码没有显示 multer 中间件。请添加足够的代码以使示例更易于调试。
  • 感谢您与我们联系!我将 / 添加到图像中,但仍然得到相同的结果。你建议我删除 const url = req.protocol + '://' + hostname + req.body.path; ?
  • 我已添加其他文件中的代码以提供更多信息。
  • 您的网址已损坏@GODSWILL 它应该读为const url = req.protocol + '://' + hostname + ":" + PORT + req.path。您正在使用req.body.path,您可以看到它已损坏,因为它在您的屏幕截图中返回未定义。您应该使用 req.pathreq.originalUrl 取决于您感兴趣的 url 对象的部分
  • 谢谢@rags2riches,我需要为 PORT 创建一个新变量吗?

标签: node.js express postman multipartform-data multer


【解决方案1】:

经过多次尝试和失败,我终于想通了。 事实证明它存在兼容性问题,具体取决于您的操作系统。

我使用的是 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

感谢这个伟大的社区。​​p>

【讨论】:

    猜你喜欢
    • 2018-04-27
    • 2023-03-03
    • 1970-01-01
    • 2017-02-10
    • 2018-12-19
    • 2021-02-10
    • 2023-01-07
    • 2017-12-22
    • 1970-01-01
    相关资源
    最近更新 更多