nodejs模拟http-post文件的方法示例

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

function PostFileToServer(sFileName, data, callback) {
    var boundary = "NODEJSPOSTFILE-" + (Math.random() * 9007199254740992).toString(36);

    var sHeader = "--" + boundary + "\r\n";
    sHeader += "Content-Disposition: form-data; name=\"fileName\"; filename=\"" + sFileName + "\"\r\n";
    sHeader += "Content-Type: application/octet-stream\r\n\r\n";

    var sEndData = "\r\n--" + boundary + "--\r\n\r\n";

    var options = {
        hostname: "127.0.0.1",
        port    : 3031,
        path    : "/cgi-bin/upload?action=uploadFile&newname=my.jpg",
        method  : 'POST'
    };

    var httpreq = http.request(options, function (httpres) {
        httpres.on('data', function (dataResponse) {
            var response = JSON.parse(dataResponse);
            console.log(response.md5);
            console.log(response.name);
        });
    });
    httpreq.setHeader('Content-Type',   'multipart/form-data; boundary=' + boundary + '');
    httpreq.setHeader('Content-Length', Buffer.byteLength(sHeader) + data.length + Buffer.byteLength(sEndData));

    httpreq.on('error', function(e) {
        console.log('problem with request: ' + e.message);
        callback(e);
        return;
    });

    httpreq.write(sHeader);
    httpreq.write(data);
    httpreq.write(sEndData);
    httpreq.end();
}

fs.readFile('1.jpg', function (err, data) {
    if (err) throw err;
    console.log(data.length);
  
    PostFileToServer("1.jpg", data, function(){
        console.log("call back");    
    });
});
{ 
    fileName:
    { 
        domain: null,
        _events: {},
        _maxListeners: undefined,
        size: 595284,
        path: 'tmp\\upload_ba227eaf1015fda43ea4a218b2161748',
        name: '1.jpg',
        type: 'application/octet-stream',
        hash: null,
        lastModifiedDate: Sun Mar 08 2015 14:34:18 GMT+0800 (中国标准时间),
        _writeStream:
        { 
            _writableState: [Object],
            writable: true,
            domain: null,
            _events: {},
            _maxListeners: undefined,
            path: 'tmp\\upload_ba227eaf1015fda43ea4a218b2161748',
            fd: null,
            flags: 'w',
            mode: 438,
            start: undefined,
            pos: undefined,
            bytesWritten: 595284,
            closed: true 
        } 
    } 
}
posted @ 2014-06-15 22:09  酱油和醋  阅读(1047)  评论(0编辑  收藏  举报