首页 > 解决方案 > 如何以相同的形式上传文件和文本输入?

问题描述

我正在尝试上传图像以及一些文本输入。(如果用户给出)

我已经这样写了我的表格

<form action="/user/upload" method="POST" enctype="multipart/form-data">
    <input type="text" placeholder="Type Something" name="message" />
    <input type="file" name="img" id="image" accept="image/*" />
    <button type = "submit">SUBMIT</button>
</form>

在服务器端。我无法阅读res.body我得到res.body的ie null。我能够管理上传的文件。但只有文本输入是问题。

有人可以帮我解决这个问题吗?

我正在使用expresswithmulter进行文件上传。这是我的服务器端代码。

const storage = multer.diskStorage({
  // destination: "./public/posts/",
  destination: (req, file, callback) => {
    const imageFileTypes = /jpeg|jpg|png|gif/;
    const videoFileTypes = /mp4/;
    let storagePath;

    if (imageFileTypes.test(path.extname(file.originalname))) {
      storagePath = "./public/posts/";
      return callback(null, storagePath);
    } else if (videoFileTypes.test(path.extname(file.originalname))) {
      storagePath = "./public/videos/";
      return callback(null, storagePath);
    } else {
      callback("ERROR: Invalid File Type");
      return;
    }
  },
  filename: function (req, file, cb) {
    // FIELD NAME IS THE NAME YOU ASSIGNED TO THE INPUT FIELD IN EJS FILE
    cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname));
  },
});

const upload = multer({
  storage: storage,
  // limits: {fileSize: 1000000}
  fileFilter: (req, file, cb) => {
    //CUSTOM FUNCTION TO CHOOSE ONLY IMAGE AND VIDO FILES
    checkFileType(file, cb);
  },
}).single("img");

const checkFileType = (file, cb) => {
  const imageFileTypes = /jpeg|jpg|png|gif/;
  const videoFileTypes = /mp4/;
  //CHECK THE EXTENCTION
  const isImageExtenction = imageFileTypes.test(path.extname(file.originalname).toLowerCase());
  const isVideoExtenction = videoFileTypes.test(path.extname(file.originalname).toLowerCase());
  //CHECK THE MIME TYPE
  const isImageMimeType = imageFileTypes.test(file.mimetype);
  const isVideoMimeType = videoFileTypes.test(file.mimetype);

  if ((isImageExtenction && isImageMimeType) || (isVideoExtenction && isVideoMimeType)) {
    return cb(null, true);
  } else {
    return cb("Invalid file type");
  }
};
//**************************THIS IS THE UPLOAD ROUTE*************
router.post("/upload", async (req, res) => {
  upload(req, res, err => {
    if (err) {
      res.send("file upload failed");
      return;
    } else {
      // console.log(req.file);
      console.log(req.body.name);
      res.send("file uploaded");
    }
  });
});

标签: javascripthtmlnode.jsforms

解决方案


推荐阅读