web端上传图片、文件等流化数据,一般使用form表单方式,或者通过 Ajax 方式上传时就使用 FormData 来承载流化数据。具体可以参考AJAX 图片上传功能实现(点击,拖拽,粘贴)Koa 服务端
同时也存在需要使用 Node 操作方式上传文件到 http 服务器上,下文详细记载。
node 端添加 request
依赖库
javascriptnpm install request
文件上传操作
javascriptconst path = require('path'); const fs = require('fs'); const request = require('request'); let files = fs.readdirSync(path.join(__dirname, 'dist')); let needUploads = []; //收集需要上传的文件 files.forEach(async name => { needUploads.push(fs.createReadStream(path.join(__dirname, `dist/${name}`))); }); //上传操作 request.post( { url: 'https://localhost:3000/upload', formData: needUploads }, (err, httpResponse, body) => { console.log('Upload successful! Server responded with:', body); }, );
服务器代码
javascript... const koaBody = require('koa-body'); ... app.use( koaBody({ multipart: true, }), );
服务器业务代码
javascriptconst router = require('koa-router')(); const fs = require('fs'); const path = require('path'); //接受上传文件接口 router.post('/upload', async (ctx, next) => { const files = ctx.request.files; for (let key in files) { let file = files[key]; const reader = fs.createReadStream(file.path); // 创建可读流 const upStream = fs.createWriteStream( path.resolve(__dirname, `../public/${file.name}`), ); reader.pipe(upStream); } ctx.response.status = 200; ctx.body = { code: 200, }; }); module.exports = router;