nodejs test file upload

 

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

}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。