更新:我已经使用 multipart (app.use(multipart({uploadDir: __dirname + '/../uploads'})) 或多或少解决了问题
来自 these instructions ),但仍然不知道为什么我的原始代码(如下)失败。
这个问题有很多变体,我尝试过其中的想法但没有成功。我正在使用 file uploading directive (并且此后尝试了另一种开源替代方案)将二进制文件发送到 Node 服务器,该服务器运行以下代码(基于我现在无法重新找到的SO答案):
exports.receive = function(req, res) {
var fitFileBuffer = new Buffer('');
// req.setEncoding("binary"); //doesn't help
req.on('data', function(chunk) {
fitFileBuffer = Buffer.concat([fitFileBuffer, chunk]);
});
req.on('end', function() {
fs.writeFileSync(
"today2.fit",
fitFileBuffer,
'binary');
res.send(200);
});
};
如果我上传 today.fit
并与 today2.fit
进行比较,它们具有相同的 Kb 数据,但不相同,后续代码无法处理文件。鉴于这种情况发生在两段第三方代码上,我怀疑问题出在我的代码上。
以下是客户端发出的 POST 的详细信息
最佳答案
最后,当我意识到我想避免保存到磁盘时,我使用 busyboy 网站上的一些内容和我自己使用的缓冲区修改了 Generalhenry 的代码:
exports.receive = function (req, res, next) {
var busboy = new Busboy({ headers: req.headers });
var fileBuffer = new Buffer('');
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
file.on('data', function(data) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
fileBuffer = Buffer.concat([fileBuffer, data]);
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
genXmlFromString(fileBuffer.toString(), function(data) {
res.json(data);
});
});
});
busboy.on('finish', function() {
console.log("'finish'");
});
req.pipe(busboy);
};
关于angularjs - 使用 Node Buffer 或 fileStream 进行 formData 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27680258/