node.js 使用http post 向服务端上传文件

function upload2(id){

console.log("开始上传");
var localpath = "文件路径";
var remotepath = "文件路径";

var localname = "local" +id+".webm";

var remotename = "remote" +id+".webm";

var boundaryKey = '----WebKitFormBoundary' + new Date().getTime();

var options = {
host:"127.0.0.1",//远端服务器域名
port:80,//远端服务器端口号
method:'POST',
path:'/upload',//上传服务路径
headers:{
'Content-Type':'multipart/form-data; boundary=' + boundaryKey,
}
};

var req = http.request(options,function(res){
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log(boundaryKey);
console.log('body: ' + chunk);
});
res.on('end',function(){
hebing(id);
console.log('res end.');
});
});

req.write(
'--' + boundaryKey + ' ' +
'Content-Disposition: form-data; name="file"; filename='+remotename+' ' +
'Content-Type:video/webm '
);

var fileStream = fs.createReadStream(remotepath,{bufferSize:1024 * 1024 * 50});
fileStream.pipe(req,{end:false});
fileStream.on('end',function(){
req.end(' --' + boundaryKey + '--');
});
}

原文地址:https://www.cnblogs.com/fengyifengceaser/p/7366055.html