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();
}
回复 (8)
M
multipart/form-data 的body部分不是纯的文件内容,要有boundary(就是header中的),去看看相关规范吧。
D
嗯,needle确实封装的不错,学习中……
D
request模块吧,用着挺好 https://github.com/mikeal/request
D
J
superagent 怎么样.. 话说中午刚翻到这个模块
http://visionmedia.github.com/superagent/#piping-data
D
J
引用 jiyinyiyongsuperagent 怎么样.. 话说中午刚翻到这个模块 http://visionmedia.github.com/superagent/ piping data
@DolphinBoy 官方的模块 Wiki 里有 HTTP 这个分类, 找一下其实比较方便的
D
引用 jiyinyiyongsuperagent 怎么样.. 话说中午刚翻到这个模块 http://visionmedia.github.com/superagent/ piping data
@jiyinyiyong 是的,平时忽略了这一部分!
参与回复
登录后即可参与回复。登录