客户端
let file = {path: '文件路径', file: '文件名字'}
const req = http.request({
host:'localhost',
port:3000,
method:'POST',
path:'/upload',
headers:{
'Content-Type':'multipart/form-data',
'Connection':'keep-alive',
'file': file.file
}
}, res => {
if (res.statusCode < 200 || res.statusCode >= 300) {
return 'statusCode=' + res.statusCode
}
else{
res.on('data', chunk => {
console.log(chunk)
});
res.on('end', (err, res) => {
console.log(err, res)
})
}
})
const fileStream = fs.createReadStream(file.path, { bufferSize: 1024 * 1024 });
fileStream.pipe(req, { end: false });
fileStream.on('end', () => {
req.end()
});
服务端
router.post('/upload', async (ctx, next) => {
ctx.body = 'success'
let buffers = [];
console.log(ctx.request.headers)
ctx.req.on('data',(trunk) => {
buffers.push(trunk);
}).on('end',async () => {
const buffer= Buffer.concat(buffers);
fs.writeFileSync(ctx.request.headers.file, buffer);
return ctx.res.end();
}).on('close', () => {
}).on('error', () => {
});
})