码迷,mamicode.com
首页 > Web开发 > 详细

Node js test http upload (multipart/form-data)

时间:2015-03-06 16:12:09      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

 

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;
}

 

Node js test http upload (multipart/form-data)

标签:

原文地址:http://www.cnblogs.com/eturn/p/4318399.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!