Multer文件上传错误

时间:2017-12-13 18:06:22

标签: node.js mongodb express multer

我正在使用multer上传文件,当我尝试上传文件时,它显示错误以下是我的代码

var multer = require('multer');

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '../public/uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
});

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

我在ejs视图中的表单是

<form action="class/<%= record.Class_Name %>/detial" method="post" enctype="multipart/form-data">
     <input type="text" name="UploaderName">
     input type="text" name="Title" >
     <input type="file" name="ThesisFile">
      <button type="submit">Choose File</button>
 </form>

我的路线代码是

router.post('/Class/:name/detial' , isLoggedIn , upload.single('ThesisFile') , function(req ,  res , next) {
  var Name = req.body.UploaderName;
  var Title = req.body.Title;
  var file = req.body.ThesisFile;
  var thesis = {
    Submitted_By: Name,
    Title : Title,
    File: file
  };
  ClassModel.findOne({ Class_Name : req.params.name } , function(err , record) {
    record.ClassFiles.push(thesis);
        record.save().then(function(record) {
          req.flash('sucess_msg' , 'Thesis Added Sucessfully');
          res.render('class' , {
            "record" : record
          });
        });
  });
});

当我提交表单时,它会向我显示以下错误 enter image description here

1 个答案:

答案 0 :(得分:0)

<form id="myForm" name="myForm" action="class/<%= record.Class_Name %>/detial" method="POST" enctype="multipart/form-data">
  <input type="text" name="uploaderName">
  <input type="text" name="title" >
  <input type="file" id="thesisFile" name="thesisFile">
  <button type="submit">Upload</button>
</form>

您可以在JavaScript中处理请求,而不是在html中执行此操作。

const $ = (selector) => {
  return document.querySelector(selector);
};

const submit = (event) => {
  event.preventDefault();
  const form = $("#myForm");
  const thesisFile = $("#thesisFile").files[0];

  const oData = new FormData(form);

  const request = new XMLHttpRequest();

  // replace "/Class/:name/detial" appropriately
  request.open("POST", "/Class/:name/detial", true);

  request.onload = (event) => {
    if (request.status === 200) {
      // do something
    } else {
      console.log("Error occurred");
    }
  };

  request.send(oData);
};

const form = document.forms.namedItem("myForm");
form.onsubmit = submit;