在Node.js中执行joi验证后,如何实现Multer在服务器上上传图像?

时间:2019-08-30 10:35:34

标签: node.js express multer cloudinary joi

我想使用Multer将图像上传到Cloudinary服务器。我的实现未按我想要的方式工作。我将用于multer和cloudinary的中间件制作为:

中间件

const cloudinary = require("cloudinary");
const cloudinaryStorage = require("multer-storage-cloudinary");

cloudinary.config({
//My Cloudinary Data
});

exports.cloudinaryStorage = cloudinaryStorage({
  cloudinary,
  folder: "game_zone",
  allowedFormats: ["jpg", "png", "jpeg", "gid", "pdf"],
  filename: function(req, file, cb) {
    cb(null, Date.now() + file.originalname); // The file on cloudinary would have the same name as the original file name
  }
});

在我的路线中,即 game.js 我也在

中通过了中间件
const multer = require("multer");
const { Category } = require("../models/category");
const { Game, validate } = require("../models/games");
const { cloudinaryStorage } = require("../middleware/cloudStorage");

const upload = multer({ storage: cloudinaryStorage });


router.post("/", upload.array("gameImage", 5), async (req, res) => {
  const { error } = validate(req.body);
  if (error) return res.status(400).send(error);
  let categories = [];
  categories = req.body.category_id;

  let category = await Category.findById({ _id: req.body.category_id });

  if (!category) return res.status(400).send(`category invalid`);

  let game = new Game({
    name: req.body.name,
    category: {
      _id: category._id,
      name: category.name
    },
    img: req.file.url
  });
  const result = await game.save();
  res.send(result);
 });

上传有效,但是当joi没有抛出任何错误时,它应该上传图像。

0 个答案:

没有答案