使用节点缓冲区或fileStream与formDatafile upload

更新 :我已经或多或less地使用multipart( app.use(multipart({uploadDir: __dirname + '/../uploads'}))从这些说明中解决了这个问题),但仍然不知道为什么我的原始代码下面)失败。

在这个问题上有很多变化,我尝试了那里没有成功的想法。 我正在使用file upload指令 (并尝试另一种开源替代方法)将二进制文件发送到节点服务器,该节点服务器运行以下代码(基于我现在无法获得的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并与today.fit进行比较,它们具有相同的Kb数据,但是不完全相同,并且随后的代码无法处理该文件。 鉴于这发生了两件第三方代码,我怀疑问题在于我的代码。

以下是POST正在进行的客户端的详细信息 网络设置

更新 :客户端的post细节帮助。 你没有发布一个文件stream(这将工作),你张贴表单stream。 好消息是有很好的处理表单stream的模块。

您需要将请求stream传送到表单处理stream(例如------WebKitFormBoundary. . . ),这将处理------WebKitFormBoundary. . . ------WebKitFormBoundary. . . 部分和他们给你的文件(S)作为stream(S)

https://github.com/mscdex/busboy

 var Busboy = require('busboy'); exports.receive = function(req, res, next) { var busboy = new Busboy({ headers: req.headers }); busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { var fileWriteStream = fs.createWriteStream('today2.fit'); file.pipe(fileWriteStream); }); busbody.on('finish', function() { res.send(201); }); req.pipe(busboy); }; 

最后,当我意识到我想避免保存到磁盘,所以我修改了一些来自busyboy站点的东西的代码和我自己使用的缓冲区:

 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); };