有效负载字节与实际字节不同

我有一个问题,当用户发送图像数据,它保存在服务器上的损坏。

所以,我基本上有这样的设置:

- api . index.js - methods . users.js 

(我已经删除了与问题无关的文件)

在API文件之外,有一个server.js ,每当访问api.example.com时都会启动它。 (基本上像一个VirtualHost)


话虽如此。 这是问题:

./api/index.js (问题点)

 // All this essentiall does is get the get the whole payload as a buffer. req.on("data", function(chunk){ // Potential problem area. req.api.payload = ((req.api.payload) ? (Buffer.concat([req.api.payload, chunk])) : (chunk)); }); 
 req.on("end", function(){ // Check if we're on api.example.com/users/ if (path[0].match(/^users$/i)) { methods.users(req, res); } }); 

我认为这个问题是在有效载荷的时候。

但是…只要incase,我会包括./api/methods/users.js …(只包括问题可能出现的部分,因为它是一个大文件)

./api/methods/users.js

 else if (req.method.match(/^POST$/i)) { if (!path[2] || path[2].match(/^(?:info|data)$/i)) { // ... (Everything that was here didn't apply to the image upload) } else if (path[2].match(/^(?:pic|picture|avatar)$/i)) { // Url matches api.example.com/users/<user_id>/pic var __base = "/home/user/web/hosts/resources/static/images/api/users/"; // Upload path // Another potential spot where the problem could be. fs.writeFile(__base + path[1] + ".png", req.api.payload, "binary", function(err){ if (err) res.api.end(err); res.api.end(req.api.payload.slice(0, 40)); // Testing }); } } 

请注意,这只是为了testing上传,我意识到有人可以上传其他数据,但这是本地的。 现在只是testing上传的数据。

另外需要注意的是,你没有明确定义的variables与问题无关,只是没有:

  • path :URL作为数组例如"/user/xero/info" – > ["user", "xero", "info"]
  • req.api :手头创build的对象(在主server.js文件中)。

还有一点需要注意的是,我正在通过cURL命令上传文件:

 curl -X POST -d @random.png http://api.poweredrails.org/users/test4/pic 

问题是你的curl用法,你需要指定--data-binary而不是-d 。 你还应该设置一个Content-Type头,这样curl就能做正确的事情:

 curl -X POST -H“Content-Type:image / png”--data-binary @ random.png http://api.poweredrails.org/users/test4/pic

另一个select是支持在后端应用程序中使用multipart / form-data,特别是如果想要提交其他信息的图像。 那么你的curl使用将如下所示:

 curl -X POST --form“mypicture=@random.png”--form“foo = bar”http://api.poweredrails.org/users/test4/pic