【发布时间】:2014-10-19 22:59:35
【问题描述】:
所以我尝试在 Node.js 中编写一个基本的文件服务器,而我尝试上传和存储在其上的所有图像都以损坏的形式返回。这个问题似乎与节点缓冲区处理转换为 UTF-8 并再次转换回来的方式有关(我必须这样做才能将 POST 正文标头从二进制数据中取出)。
这是一个简单的 Node 服务器,显示了我当前的方法和我遇到的问题:
var http = require('http');
var server = http.createServer(function(request, response) {
if (request.method === "GET") {
// on GET request, output a simple web page with a file upload form
var mypage = '<!doctype html><html><head><meta charset="utf-8">' +
'<title>Submit POST Form</title></head>\r\n<body>' +
'<form action="http://127.0.0.1:8008" method="POST" ' +
'enctype="multipart/form-data"> <input name="upload" ' +
'type="file"><p><button type="submit">Submit</button>' +
'</p></form></body></html>\r\n';
response.writeHead(200, {
"Content-Type": "text/html",
"Content-Length": mypage.length
});
response.end(mypage);
} else if (request.method === "POST") {
// if we have a return post request, let's capture it
var upload = new Buffer([]);
// get the data
request.on('data', function(chunk) {
// copy post data
upload = Buffer.concat([upload, chunk]);
});
// when we have all the data
request.on('end', function() {
// convert to UTF8 so we can pull out the post headers
var str = upload.toString('utf8');
// get post headers with a regular expression
var re = /(\S+)\r\nContent-Disposition:\s*form-data;\s*name="\w+";\s*filename="[^"]*"\r\nContent-Type: (\S+)\r\n\r\n/i,
reMatch = str.match(re);
var lengthOfHeaders = reMatch[0].length,
boundary = reMatch[1],
mimeType = reMatch[2];
// slice headers off top of post body
str = str.slice(lengthOfHeaders);
// remove the end boundary
str = str.replace("\r\n" + boundary + "--\r\n", '');
// convert back to buffer
var rawdata = new Buffer(str, 'utf8');
// echo back to client
response.writeHead(200, {
"Content-Type": mimeType
});
response.end(rawdata);
});
}
});
server.listen(8008);
console.log("server running on port 8008");
要对其进行测试,请在节点中运行脚本并在浏览器中转到 127.0.0.1:8008。尝试上传图片并提交表单。图像每次都以损坏的形式返回 - 即使脚本应该直接将图像数据回显到浏览器。
那么有谁知道我在这里做错了什么?有没有更好的方法来处理我还没有想到的 Node 中的 POST 正文标头? (在任何人说什么之前,不,我不想想使用 Express。我想弄清楚并理解这个问题。)
【问题讨论】:
标签: javascript node.js utf-8