Node.js使用Formidable报错:Cannot read properties of undefined (reading 'filepath')
解决Formidable上传文件时
Cannot read properties of undefined (reading 'path')错误 问题重现
使用Formidable上传文件并修改存储目录时,出现Cannot read properties of undefined (reading 'path')错误。已尝试调换fields和files参数,文件大小仅几KB,排除大小限制问题,代码如下:
var http = require("http"); var fs = require("fs"); var formidable = require("formidable"); http.createServer(function (req, res) { if (req.url == "/fileupload") { var form = new formidable.IncomingForm(); form.parse(req, function (err, fields, files) { var oldpath = files.filetoupload.path; var newpath = "C:/Users/devsi/" + files.filetoupload.originalFilename; fs.replace(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="fileupload"><br>'); res.write('<input type="submit">'); res.write("</form>"); return res.end(); } }).listen(8080);
错误原因
- 表单字段名拼写不匹配:HTML中文件输入框的
name属性是fileupload,但代码中却尝试读取files.filetoupload,字段名拼写错误导致files.filetoupload为undefined,进而读取path时抛出错误。 - Formidable版本兼容问题:Formidable v3+版本中,单文件上传的字段也会以数组形式返回,需通过
files.fileupload[0]获取文件对象,而非旧版的files.fileupload。 - 文件操作方法错误:Node.js的
fs模块中不存在fs.replace方法,应该使用fs.rename(同分区移动)或fs.copyFile+fs.unlink(跨分区或更稳妥的文件转移)。
修正后的代码
var http = require("http"); var fs = require("fs"); var formidable = require("formidable"); http.createServer(function (req, res) { if (req.url == "/fileupload") { var form = new formidable.IncomingForm(); form.parse(req, function (err, fields, files) { // 处理版本兼容,获取文件对象 const file = files.fileupload[0]; const oldpath = file.filepath; const newpath = `C:/Users/devsi/${file.originalFilename}`; // 使用fs.copyFile配合unlink完成文件转移(跨分区更可靠) fs.copyFile(oldpath, newpath, (err) => { if (err) throw err; // 复制完成后删除临时文件 fs.unlink(oldpath, (unlinkErr) => { if (unlinkErr) throw unlinkErr; 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="fileupload"><br>'); res.write('<input type="submit">'); res.write("</form>"); return res.end(); } }).listen(8080);
额外说明
- 若使用Formidable v2及以下版本,文件对象可直接通过
files.fileupload获取,无需取数组下标,但建议升级到新版并适配数组形式以支持多文件上传。 - 确保目标目录
C:/Users/devsi/存在,否则需先通过fs.mkdir创建目录。
内容的提问来源于stack exchange,提问作者Hideki Namikawa
相关产品推荐
相关产品推荐

