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

nodejs test file upload

时间:2015-03-18 17:29:29      阅读:634      评论:0      收藏:0      [点我收藏+]

标签:

 

var http = require("http");
var url = require("url");
var fs = require("fs");

var server = http.createServer(function(req, res) {

    var boundary = getBoundary(req);

    var endStr = "--" + boundary + "--";

    var tmpFileName = __dirname + "/upload/" + Math.random() + ".tmp"
    var fileStream = fs.createWriteStream(tmpFileName);
    var transform = require("stream").Transform;
    var parser = new transform();
    parser.headers = undefined;
    parser._transform = function(chunk, encoding, callback) {
        if (this._fileStart) {
            wrtieToEnd(chunk, endStr, this);
            //this.push(chunk);
        } else {
            var i = chunk.toString().indexOf("\r\n\r\n");
            if (i >= 0) {
                this._fileStart = true;
                this.headers = chunk.toString().slice(0, i);
                //console.log(this);
                wrtieToEnd(chunk.slice(i + 4), endStr, this);
            }
        }
        callback();
    }

    req.on("end", function() {
        var fileName = __dirname + "/upload/" + parseFilename(parser.headers);
        //console.log(fileName);
        fs.rename(tmpFileName, fileName, function() {});
    });
    req.pipe(parser).pipe(fileStream);

    res.end(req.url);
});

// Server would listen on port 
server.listen(8889);


//////////////////////////////////////
function wrtieToEnd(chunk, endStr, transform) {
    var len = chunk.length - endStr.length - 100;
    var i = chunk.toString("utf8",len).indexOf(endStr);
    if (i >= 0) {
        transform.push(chunk.slice(0, len + i));
    } else {
        transform.push(chunk);
    }
}

function parseFilename(head) {
    //---------------------------acebdf13572468
    //Content-Disposition: form-data; name="fieldNameHere"; filename="Explorer.7z"
    //Content-Type: application/octet-stream
    var arr = head.split(‘\r\n‘);
    var arr2 = arr[1].split(‘;‘);
    var name = arr2[2].split(‘=‘)[1].replace(/"/g, ‘‘);
    return name;
}

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

}

 

nodejs test file upload

标签:

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

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