exports.uploadFileToServer = function(filepath) {
var headers = { //定义符合上传API的请求头
'Content-Type': 'multipart/form-data;boundary=------------ei4Ij5Ef1ae0ae0Ij5Ij5Ij5Ij5GI3',
'Content-Length': '1049', 'Connection': 'Keep-Alive', 'Pragma', 'no-cache' };
var reqos = {
host: 'xxx.com',
port: 80,
path: '/fileupload',
method: 'POST',
headers: headers
};
var req = http.request(reqos, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) { //得到返回结果
console.log('BODY: ' + chunk);
});
});
// 向 request 体里面写入数据,只能是 string 或者 buffer
//req.write(filepath);
//我们要上传一个文件,所以要用到读取流
//创建一个文件读取流
var readStream = fs.createReadStream(filepath);
readStream.on('open', function () {
// 等待读取流打开,然后写入到 req 对象中
readStream.pipe(req);
});
// 捕获错误
readStream.on('error', function(err) {
req.end(err);
});
req.end();
}
9 回复