[英]Payload bytes different from actual bytes
我有一个问题,当用户发送图像数据时,它已损坏地保存在服务器上。
所以,我基本上有这个设置:
- 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);
}
});
我认为问题出在有效载荷时。
但是... ./api/methods/users.js
万一,我将包括./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
});
}
}
请注意,这只是为了测试上传,我意识到有人可以上传其他数据,但这是本地的。 目前,它仅用于测试上传的数据。
另外请注意,您没有看到明确定义的任何变量都与问题无关,仅此而已:
path
:作为数组的网址,例如"/user/xero/info"
-> ["user", "xero", "info"]
req.api
: req.api
创建的对象(在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
另一个选择是支持在后端应用程序中使用multipart / form-data,尤其是如果要与图像一起提交其他信息时。 然后,您的curl用法将如下所示:
curl -X POST --form "mypicture=@random.png" --form "foo=bar" http://api.poweredrails.org/users/test4/pic
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.