【发布时间】: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