用node.js编写二进制数据时遇到的问题

我正在尝试将一个请求的二进制正文写入文件并失败。 该文件在服务器上创build,但我无法打开它。 我在Ubuntu上遇到“致命错误:不是png”。 以下是我提出的要求:

curl --request POST --data-binary "@abc.png" 192.168.1.38:8080 

这里是我如何试图保存它的文件。 第一个片段是将所有数据附加在一起的中间件,第二个片段是请求处理程序:

中间件:

 app.use(function(req, res, next) { req.rawBody = ''; req.setEncoding('utf-8'); req.on('data', function(chunk) { req.rawBody += chunk; }); req.on('end', function() { next(); }); }); 

处理器:

 exports.save_image = function (req, res) { fs.writeFile("./1.png", req.rawBody, function(err) { if(err) { console.log(err); } else { console.log("The file was saved!"); } }); res.writeHead(200); res.end('OK\n'); }; 

这里有一些可能有用的信息。 在中间件中,如果我loggingrawBody的长度,它看起来是正确的。 我真的坚持如何正确保存文件。 我所需要的只是一个正确的方向。

谢谢。

这是一个完整的快速应用程序的作品。 我打了curl --data-binary @photo.jpg localhost:9200 ,它工作正常。

 var app = require("express")(); var fs = require("fs"); app.post("/", function (req, res) { var outStream = fs.createWriteStream("/tmp/upload.jpg"); req.pipe(outStream); res.send(); }); app.listen(9200); 

我只是直接把请求传给文件系统。 至于你的实际问题,我的第一个猜测是req.setEncoding('utf-8'); 因为utf-8用于文本数据而不是二进制数据。

为了修复你的代码:我与@Peter Lyons ,错误可能是req.setEncoding('utf-8'); 线。

我知道以下不直接提出你的问题,而是使用Express.js提供的req.filesfunction来提供替代方法。

如果(req.files.photo && req.files.photo.name){//获取文件的临时位置。 var tmp_path = req.files.photo.path;

 // set where the file should actually exists - in this case it is in the "images" directory. var target_path = './public/profile/' + req.files.photo.name; // Move the file from the temporary location to the intended location. fs.rename(tmp_path, target_path, function (error) { if (!error) { /* * Remove old photo from fs. * You can remove the following if you want to. */ fs.unlink('./public/profile/' + old_photo, function () { if (error) { callback_parallel(error); } else { callback_parallel(null); } }); } else { callback_parallel(error); } }); 

}