我正在使用 Node.JS 构建一个 Web 应用程序,至少应该允许用户上传 Excel 电子表格 (.xlsx),然后使用 Excel 解析器(当前使用 node-xlsx - https://www.npmjs.org/package/node-xlsx ),我希望能够找到该文件,解析它,并将其内容打印到控制台。到目前为止,我已上传并存储文件,但在指定我的应用程序应搜索的文件路径时遇到问题。
我相信我的麻烦是我试图在服务器端执行此操作,并且我告诉我的应用程序在没有访问权限时在用户目录中搜索该文件。
这里是示例代码:
var fullfile;
app.post('/upload', function (request, response) {
var fstream;
request.pipe(request.busboy);
request.busboy.on('file', function (fieldname, file, filename) {
console.log('Uploading: ' + filename);
fstream = fs.createWriteStream('./storedFiles/' + filename);
file.pipe(fstream);
fstream.on('close', function () {
response.redirect('success');
console.log('Uploaded to ' + fstream.path);
fullfile=fstream.name;
var obj = xlsx.parse(__dirname + fullfile);
console.log(obj);
});
});
});
这会产生错误:
返回绑定(bind).open(pathmodule._makelong(path) stringtoflags(flags) 模式) 错误:ENOENT,没有这样的文件或目录“C\Users(此处是我本地计算机上的文件路径)”
有人能指出我缺少的一种方法吗?我觉得这与 fs 方法有关。
谢谢
最佳答案
首先,不要使用用户在保存文件时提供的文件名 - 您将得到重复的文件名,并且可能存在安全风险(通常,永远不要信任用户提供的数据)。只需使用您自己的值即可 - 使用您自己的命名约定来防止重复或使用操作系统提供的 tmp 文件更为标准。
要解决您的问题,请尝试:
需要在文件顶部添加路径
:
var path = require('path');
并将 fullfile
的值更改为:
fullfile = path.join(__dirname,fstream.path)
然后将fullfile
传递给xlsx.parse
:
var obj = xlsx.parse(fullfile);
关于javascript - 查找相对文件路径来解析 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24412594/