【发布时间】:2020-12-25 10:10:41
【问题描述】:
我有这个用于将产品添加到数据库的快速后端,现在我已经将它配置为获取产品图像,然后是名称、价格、类型和颜色,到目前为止它运行良好。但现在我正在努力让它不能拍摄一张图像,而是最多四张,但我一直遇到问题。单张图片的初始代码如下
首先是 Cloudinary 的配置
const express = require("express");
const cloudinary = require("cloudinary").v2;
const { CloudinaryStorage } = require("multer-storage-cloudinary");
const multer = require("multer");
const verify = require("../routes/verifyToken");
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET,
});
const storage = new CloudinaryStorage({
cloudinary: cloudinary,
params: {
folder: "Shoes",
format: async (req, file) => {
"jpg", "png";
}, // supports promises as well
public_id: (req, file) => {
console.log(
new Date().toISOString().replace(/:/g, "-") + file.originalname
);
return (
new Date().toISOString().replace(/:/g, "-") + file.originalname
);
},
},
});
const parser = multer({ storage: storage });
然后是发布鞋子(产品)的发布请求。
router.post("/post/menshoe", verify,parser.single("shoeImage"), async (req, res) => {
// console.log(req.file);
if (!req.file) return res.send("Please upload a file");
// console.log(req.file); // to see what is returned to you
const image = {};
console.log(req.file)
const shoeUpload = new MenShoe({
shoeImage: req.file.path,
name: req.body.name,
type: req.body.type,
price: req.body.price,
color: req.body.color,
});
console.log(shoeUpload);
try {
const shoe = await shoeUpload.save();
res.json({ msg: "Shoe uploaded", success: true, shoe });
} catch (err) {
console.log(err);
res.json({
msg: "Failed to upload",
success: false,
err,
});
}
}
);
我想指出,我试图研究一种方法,但我遇到的每个答案都使用完全不同的方式来发布图像,我正在认真尝试避免从头开始写这个,因为我已经写了很多这样的代码。如果有人可以通过对这段代码进行一些调整来帮助我实现这一目标,我将不胜感激。
提前致谢
【问题讨论】:
-
你必须描述你面临什么样的问题。你的问题太宽泛了
-
@iwaduarte 我只想了解如何使用上面的代码在单个请求中上传多个图像。这就是我不知道如何使用上面的代码来做的事情
-
router.post("/post/menshoe", verify,parser.single("shoeImage"), async (req, res) => { 改成这个 "router.post("/ post/menshoe", verify,parser.array("shoeImage"), async (req, res) => {", 检查是否可以上传多张图片
-
@JatinMehrotra 我实际上在研究时看到了类似的东西,我已经尝试过了。它像这样 ``` router.post("/post/menshoe", verify,parser.array("shoeImage, 4"), async (req, res) => {``` 但它仍然没有工作
-
应该是这样的 ``` router.post("/post/menshoe", verify,parser.array("shoeImage," 4), async (req, res) => { ``, 检查引号的位置 -> " shoeimage 必须在引号中而不是 4
标签: node.js express backend multer cloudinary