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

转载于:https://www.cnblogs.com/motadou/p/3790018.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值