无法上传图片并保存在mongo中

问题描述 投票:0回答:1

我有从一个字段获取文件路径的代码,并且我已将 cloudinary 与从 cloudinary 获取链接的另一图像字段集成。简而言之,我使用 multer 在数据库中保存文件路径和图像链接。因此,令我惊讶的是,一切都运行良好(或者简而言之),但数据库不断更新,除了 ObjectId 之外没有任何字段。

这是我的控制器

const fileUpload = async (req, res) => {
try {
    const templateEntry = new Template();

    if (req.files && req.files.length > 0) {
        for (const file of req.files) {
            const fileName = file.filename;
            console.log("Processing file:", file.fieldname);
            if (file.fieldname === "imageUrl") {
                const result = await cloudinary.uploader.upload(file.path);
                if (!result.secure_url) {
                    console.log("Cloudinary upload failed:", result);
                } else {
                    console.log("Cloudinary upload successful. URL:", result.secure_url);
                    templateEntry.imageUrl = result.secure_url;
                }
            } else if (file.fieldname === "filePath") {
                const fileEntryPath = path.join(
                    __dirname,
                    "uploads",
                    fileName
                );
                console.log("File path:", fileEntryPath); // Log the file path
                templateEntry.filePath = fileEntryPath;
            }
        }
    }
    console.log("Template entry before saving:", templateEntry); // Log the template entry before saving
    await templateEntry.save();
    console.log("Template entry saved successfully");

    res.status(200).json({
        message: "Template has been saved successfully",
    });
} catch (error) {
    console.error("Error:", error); // Log the error for debugging
    res.status(500).json({ error: error.message });
}
};

这是我的路线

const multer = require("multer");
const path = require("path");
const storage = multer.diskStorage({
    destination: "./uploads",
    filename: (req, file, cb) => {
        const unique = Date.now() + "-" + Math.round(Math.random() * 1e9);
        cb(null, unique + "-" + path.extname(file.originalname));
    },
});

const upload = multer({ storage });

router.post(
    "/template-upload",
    upload.fields([
        { name: "filePath", maxCount: 1 },
        { name: "imageUrl", maxCount: 1 },
    ]),
    fileUpload
);
mongodb express multer cloudinary
1个回答
0
投票

很多改变是必要的,不确定我是否理解你的逻辑。检查这是否适合您的需求。

表格

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <form method="post" action="http://localhost:3000/template-upload" enctype="multipart/form-data" target="_blank">
      <label>imageUrl</label>
      <input type="file" name="imageUrl" />

      <br /><br />

      <label>filePath</label>
      <input type="file" name="filePath" />

      <br /><br />

      <input type="submit" />
    </form>
  </body>
</html>

服务器:

const express = require('express')
const app = express()
const mongoose = require("mongoose");
const multer = require("multer");
const path = require("path");

app.listen(3000, () => {
  console.log("Example app listening on port 3000");
})

mongoose.connect(
  "mongodb://yourmongoserver"
).then(async () => {
  console.log("Connected do DB");
}).catch(() => {
  console.log("Error while connecting to DB");
});

const Template = mongoose.model("Template", { imageUrl: String, filePath: String });

const fileUpload = async (req, res) => {
  try {
    const imageUrl = req.files?.imageUrl?.[0];
    const filePath = req.files?.filePath?.[0];

    if (imageUrl && filePath) {
      const templateEntry = new Template();

      //const result = await cloudinary.uploader.upload(imageUrl.path);
      const result = { secure_url: "dummy return URL" } //remove this line later
      if (!result.secure_url) {
        console.log("Cloudinary upload failed:", result);
      } else {
        console.log("Cloudinary upload successful. URL:", result.secure_url);
        templateEntry.imageUrl = result.secure_url;
      }

      const fileEntryPath = path.join(
        __dirname,
        filePath.path
      );
      templateEntry.filePath = fileEntryPath;

      await templateEntry.save();
      console.log("Template entry saved successfully");

      return res.status(200).json({
        message: "Template has been saved successfully",
      });
    } else {
      return res.status(400).json({
        error: "Need to upload 2 files with names 'imageUrl' and 'filePath'",
      });
    }
  } catch (error) {
    console.error("Error:", error); // Log the error for debugging
    res.status(500).json({ error: error.message });
  }
};

const storage = multer.diskStorage({
  destination: "./uploads",
  filename: (req, file, cb) => {
    const unique = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, unique + "-" + path.extname(file.originalname));
  },
});

const upload = multer({ storage });

app.post(
  "/template-upload",
  upload.fields([
    { name: "filePath", maxCount: 1 },
    { name: "imageUrl", maxCount: 1 },
  ]),
  fileUpload
);
© www.soinside.com 2019 - 2024. All rights reserved.