Use koa2 to build a file upload service, back-end code
const os = require('os'); const path = require('path'); const koaBody = require('koa-body'); const Koa = require ('koa'); const app = new Koa (); const fs = require("fs"); const main = async function(ctx) { //const tmpdir = os.tmpdir(); //return system temporary file const tmpdir = path.join(__dirname, "static"); const filePaths = []; const files = ctx.request.body.files || {}; const params = ctx.request.body.fields console.log(params); for (let key in files) { const file = files[key]; if(Object.prototype.toString.call(file) == '[object Array]'){ for(var j = 0; j < file.length; j++ ){ witeFile(file[j]); } }else{ witeFile(file); } } function witeFile(file){ const filePath = path.join(tmpdir, file.name); const reader = fs.createReadStream(file.path); const writer = fs.createWriteStream(filePath); reader.pipe(writer); filePaths.push(filePath); } ctx.body = filePaths; }; app.use(koaBody({ multipart: true })); app.use(main); app.listen(3000);
front-end code
<form action="http://localhost:3000/" method="post" enctype="multipart/form-data"> <input type="text" name="name" id="" value="姓名" /> <input type="text" name="pwd" id="" value="123456" /> <input type="file" name="file" id="file" value="" multiple="multiple" /> <input type="submit" value="提交"/> </form>