var http = require("http");
var url = require("url");
var fs = require("fs");
// fs.readFile("D:\\02_bat\\Explorer.7z", function(err, data) {
// console.log(data);
// });
var server = http.createServer(function(req, res) {
//req.setEncoding("binary");
var chunk;
var j = 0;
req.on("data", function(data) {
//console.log(data + "");
var buf = new Buffer(data, "binary");
var boundary = getBoundary(req);
var startStr = "Content-Type: application/octet-stream\r\n";
var start = getIndexInBuffer(startStr, buf) + 1;
var endStr = "--" + boundary + "--"; //"---------------------------acebdf13572468--";
var end = getIndexInBuffer(endStr, buf) - endStr.length;
var file = buf.slice(start, end);
fs.writeFile("aa.7z", file);
});
res.end(req.url);
});
// Server would listen on port
server.listen(8889);
//////////////////////////////////////
function getBoundary(req) {
//Content-Type: multipart/form-data; boundary=${bound}
var content_type = req.headers["content-type"];
var arr = content_type.split(';');
for (var i in arr) {
var str = "boundary=";
var index = arr[i].indexOf(str);
if (index > -1) {
return arr[i].substring(index + str.length);
}
}
}
function getIndexInBuffer(str, buf) {
var buf2 = new Buffer(str);
for (var i = 0; i < buf.length; i++) {
if (buf[i] === buf2[0]) {
var b = true;
for (var j = 1; j < buf2.length; j++) {
i++;
if (buf[i] === buf2[j]) {
b = true;
} else {
b = false;
break;
}
}
if (b) {
return i;
}
}
}
return -1;
}