javascript - TypeError:上传文件时无法读取Node js中未定义的属性“路径”
问题描述
我是节点 js 的新手。
我试图上传一个文件,它显示了一些路径错误。下面是我的代码。
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
console.log(files);
var oldpath = files.filetoupload.path;
var newpath = '/var/www/html/Node-Js/img/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
在这里我已经安装了强大的模块。它已经安装了。我收到以下错误,请看一下。
/var/www/html/Node-Js/file_upload.js:11
var oldpath = files.filetoupload.path;
^
TypeError: Cannot read property 'path' of undefined
at /var/www/html/Node-Js/file_upload.js:11:40
at IncomingForm.<anonymous> (/var/www/html/Node-Js/node_modules/formidable/lib/incoming_form.js:107:9)
at emitNone (events.js:106:13)
at IncomingForm.emit (events.js:208:7)
at IncomingForm._maybeEnd (/var/www/html/Node-Js/node_modules/formidable/lib/incoming_form.js:557:8)
at Object.end (/var/www/html/Node-Js/node_modules/formidable/lib/incoming_form.js:247:12)
at IncomingMessage.<anonymous> (/var/www/html/Node-Js/node_modules/formidable/lib/incoming_form.js:132:30)
at emitNone (events.js:106:13)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
解决方案
你得到null{}是console.log(files)
这个特定错误背后的原因。Files
即将为空,因此files.filetoupload
将是未定义的,这就是为什么files.filetoupload.path
找不到。我会说请找出为什么会files
为空。一旦您开始在文件中获取数据,此错误将得到解决。
推荐阅读
- python - 如何在不显示模块名称的情况下引发我的异常
- java - 了解 HashMap 中的“结构修改”
- node.js - Node JS 和 Firebase 无法使用 equal.To() 进行搜索
- html - 如何创建始终为 16:9 的另一个 html 页面的预览
- java - 如何将条件格式应用于通过数组创建的列表中的特定项目
- ios - 为已编译的框架添加 .dSYM 文件并将它们发送到 App Store Connect
- vue.js - 从 jquery 函数 Nuxt 启动回调
- javascript - 调整/更新过滤器选择以适应闪亮的 DT 数据表中已应用的过滤器
- google-maps - Vue:编辑 gmap 自定义标记
- python - 是否有一个函数可以为数据框中的每个条目创建类型的辅助数据框?