【问题标题】:Cannot upload a file to Node JS无法将文件上传到 Node JS
【发布时间】:2020-11-29 11:21:47
【问题描述】:

当我评论 app.use(fileUpload) 行时,我在 app.post 上设置的断点会从浏览器中调用。但是它遇到了一个错误,说发生了异常:TypeError: Cannot read property 'filetoupload' of undefined

但是,当 app.use(fileUpload) 语句被取消注释时,app.post 处的断点根本不会被调用。

所以,不清楚缺少什么。

const express =require('express');
const fileUpload = require('express-fileupload');

const app = express();


app.use(express.static('./public'));
app.use(fileUpload);

app.listen(9000,function() {

    console.log('My server is running on port 9000');
})

app.post('/sendFile', function(req, res) {
    let sampleFile = req.files.filetoupload;
    sampleFile.mv('./Uploads/FirstImage.jpg', function(err) {
    if (err)
        return res.status(500).send(err);
    res.send('File uploaded!');
    });
});

HTML 页面:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="Test File Upload">
      <meta name="keywords" content="Test File Upload">
    <meta name="author" content="This and That">
    <title>Welcome</title>
    <link rel="stylesheet" href="./css/style.css">
  </head>
  <body>
    <form action="/sendFile" method="POST" name="SendDetails" onsubmit="return validateForm()">

    <section id="boxes">
        <input type="file" accept="image/*" capture="environment" name='filetoupload' id="useCamera">
          <input class = 'buttons' type="submit" value="Submit photo" id='btnGoForIt' style="margin-left:30%">

    </section>
    <script src = 'home.js'></script>
  </form>
  </body>
</html>

home.js 包含以下 validateForm() 应该在提交时触发。

function validateForm() {
  var x = document.forms["SendDetails"]["filetoupload"].value;
  if (x == "") {
    alert("No image found to send to Nodejs");
    return false;
  }
}

【问题讨论】:

  • 您需要提供minimal reproducible example。我们看不到您是如何提出请求的。也许问题是上传文件,而不是从请求中读取文件
  • 谢谢。也会粘贴 HTML 代码。

标签: javascript node.js express visual-studio-code


【解决方案1】:

在表单中添加 enctype='multipart/form-data' 标签

【讨论】:

    【解决方案2】:

    试试这个app.use(fileUpload({ useTempFiles: true }));,它对我有用。

    【讨论】:

      【解决方案3】:

      你能看一下 express-fileupload的例子

      我认为这可能是由于 encType 标签或检查文件是否存在。

      【讨论】:

      • 这也是必需的。谢谢
      猜你喜欢
      • 2019-05-24
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 2022-10-16
      • 2021-08-29
      • 2020-03-15
      • 1970-01-01
      • 2021-01-16
      相关资源
      最近更新 更多