function upload(callback) {
let boundaryKey = '----' + new Date().getTime(); // 用于标识请求数据段
let options = {
host: 'localhost', // 远端服务器域名
port: 80, // 远端服务器端口号
method: 'POST',
path: `/upload`, // 上传服务路径
headers: {
'Content-Type': 'multipart/form-data; boundary=' + boundaryKey,
'Connection': 'keep-alive'
}
};
let req = http.request(options, function(res){
res.setEncoding('utf8');
res.on('data', function(chunk) {
console.log('body: ' + chunk);
});
res.on('end', function() {
console.log('res end.');
});
});
/*req.write(
'--' + boundaryKey + 'rn' +
'Content-Disposition: form-data; name="upload"; filename="test.txt"rn' +
'Content-Type: text/plain'
);*/
req.write(
`--${boundaryKey}rn Content-Disposition: form-data; name="${self.path}"; filename="${self.file}"rn Content-Type: text/plain`
);
// 创建一个读取操作的数据流
let fileStream = fs.createReadStream(this.filePath);
fileStream.pipe(req, {end: false});
fileStream.on('end', function() {
req.end('rn--' + boundaryKey + '--');
callback && callback(null);
});
}
let boundaryKey = '----' + new Date().getTime(); // 用于标识请求数据段
let options = {
host: 'localhost', // 远端服务器域名
port: 80, // 远端服务器端口号
method: 'POST',
path: `/upload`, // 上传服务路径
headers: {
'Content-Type': 'multipart/form-data; boundary=' + boundaryKey,
'Connection': 'keep-alive'
}
};
let req = http.request(options, function(res){
res.setEncoding('utf8');
res.on('data', function(chunk) {
console.log('body: ' + chunk);
});
res.on('end', function() {
console.log('res end.');
});
});
/*req.write(
'--' + boundaryKey + 'rn' +
'Content-Disposition: form-data; name="upload"; filename="test.txt"rn' +
'Content-Type: text/plain'
);*/
req.write(
`--${boundaryKey}rn Content-Disposition: form-data; name="${self.path}"; filename="${self.file}"rn Content-Type: text/plain`
);
// 创建一个读取操作的数据流
let fileStream = fs.createReadStream(this.filePath);
fileStream.pipe(req, {end: false});
fileStream.on('end', function() {
req.end('rn--' + boundaryKey + '--');
callback && callback(null);
});
}