想要使用用户使用multer指定的文件名保存文件

问题描述 投票:0回答:1
    const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const multer = require("multer");
const path = require("path");

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const app = express();

app.use(cors());
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies for form data
mongoose.connect("mongodb://127.0.0.1:27017/Gallary");

const schema = new mongoose.Schema({
  email: {
    required: true,
    type: String,
  },
  password: {
    required: true,
    type: String,
  },
});
const Login = mongoose.model("Login", schema);

app.get("/", (req, res) => {
  res.send("Gallery it is");
});

app.post("/SignUp", async (req, res) => {
  try {
    let result = await Login.find(req.body);
    if (result.length == 0) {
      let data = new Login(req.body);
      await data.save();
      res.send({ result: true });
    } else {
      res.send({ result: false });
    }
  } catch (e) {
    res.send(e);
  }
});

app.post("/Login", async (req, res) => {
  try {
    let result = await Login.find(req.body);
    console.log("came");
    if (result.length != 0) {
      res.send({ result: true });
    } else {
      res.send({ result: false });
    }
  } catch (e) {
    res.send({ result: false });
  }
});

// Define multer storage configuration
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/");
  },
  filename: (req, file, cb) => {
    console.log("place2"+req.body.filename );
    const filename = req.body.filename ? req.body.filename : `default_filename_${Date.now()}${path.extname(file.originalname)}`;
    cb(null, filename);
  },
});

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

// Define route for image upload
app.post("/upload", upload.single("image"), (req, res) => {
  console.log("Uploaded file:", req.file.filename);
  res.json({ filename: req.file.filename });
});

app.listen(process.env.PORT || 3001, () => {
  console.log("Server is running on port 3001");
});

在上面的代码中,我尝试使用 multer 保存文件,但它始终使用默认名称保存文件。 在上传路径中,它打印正确的文件名,但在 place2 标记中 当我使用控制台打印时,我变得不确定。

为什么我在 place2 console.log 中得到 {} 空对象,但是我在前端发送的上传路由中得到正确的对象或 req.body。

javascript reactjs node.js mern multer
1个回答
0
投票

根据官方文档,使用时可能无法正确填充

req.body
。除了
req.body
,您还可以尝试以下 -

使用

file.fieldname
代替
req.body.filename

按如下方式更新您的代码 -

filename: (req, file, cb) => {
    console.log("place2"+file.fieldname );
    const filename = file.fieldname ? file.fieldname : `default_filename_${Date.now()}${path.extname(file.originalname)}`;
    cb(null, filename);
  },

参考:doc

© www.soinside.com 2019 - 2024. All rights reserved.