【发布时间】:2019-05-03 22:32:49
【问题描述】:
我正在使用 FormData 上传文件并使用 Multer 在服务器端接收它。一切都按预期工作,除了因为我在前端使用 FileSystem API (https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/webkitGetAsEntry),我上传的文件来自子目录。 Multer 似乎只看到文件名,即使我在将文件附加到表单数据 (https://developer.mozilla.org/en-US/docs/Web/API/FormData/append) 时明确设置了文件的别名。似乎 Multer 在我的请求处理程序的其余部分之前执行其逻辑,并且看不到我在正文上设置的参数。如何让 multer 查看完整路径?
这是我当前设置的简化版本:
Client(alias 表示带路径的全名,file.name 是 FileSystem API 自动设置的基本名称):
function upload(file, alias) {
let url = window.location.origin + '/upload';
let xhr = new XMLHttpRequest();
let formData = new FormData();
xhr.open('POST', url, true);
return new Promise(function (resolve, reject) {
xhr.addEventListener('readystatechange', function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
resolve(file.name);
}
else if (xhr.readyState == 4 && xhr.status != 200) {
reject(file.name);
}
})
formData.append('file', file, alias || file.name); // this should in theory replace filename, but doesn't
formData.append('alias', alias || file.name); // an extra field that I can't see in multer function at all
xhr.send(formData);
});
}
服务器:
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
// neither req nor file seems to contain any hint of the alias here
cb(null, file.originalname);
}
});
const upload = multer({storage: storage});
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/upload', upload.single('file'), function (req, res, next) {
// by this time the file seems to already be on disk with whatever name multer picked
if (req.file) {
res.status(200).end();
} else {
res.status(500).end();
}
});
【问题讨论】:
-
req.body在服务器上显示什么? -
在 multer 中分配给文件名字段的函数中,它是空的,在发布请求中它包含设置的别名,但是在发布请求处理程序启动时,文件已经以原始文件写入磁盘名字。
-
file.fieldname是否被设置了别名? (在filename: function(){...}内console.log(file.fieldname)显示什么? -
file.fieldName只是设置为file,不幸的是,我在前端设置它的方式(附加的第一个参数)。如果我(作为黑客)将其设置为我想要的名称,我不确定如何从 upload.single 调用中引用它。 -
该文件来自带有 multipart/form-data 设置的表单,并且 multer 已经正确处理了文件,只是没有看到我想要重命名的别名,我什至可以确认内容正确,文件可访问。
标签: javascript node.js multer