使用koa2搭建文件上传服务,后端代码
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(); //返回系统临时文件 const tmpdir = path.join(__dirname, "static"); const filePaths = []; const files = ctx.request.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);
前端代码
使用ajax 上传
$("#file")[0].onchange = function(e){ console.log(this.files); var filse = this.files; var fd = new FormData(); fd.append("file",filse[0]); $.ajax({ type:"post", data:fd, processData:false, contentType:false, url:"http://192.168.20.104:3000", }).then(function(ret){ console.log(ret); }).catch((e)=>{ console.log(e); }) }
注意:
新版本的koa-body通过ctx.request.files获取上传的文件
旧版本的koa-body通过ctx.request.body.files获取上传的文件
另外,附上express 的文件上传:
const multiparty = require('multiparty');router.post('/file', function(req, res, next) { //生成multiparty对象,并配置上传目标路径 const form = new multiparty.Form() // //设置编辑 form.encoding = 'utf-8' // //设置文件存储路径 form.uploadDir = "./public/static/" // //设置单文件大小限制 //form.maxFilesSize = 2 * 1024 * 1024 // form.maxFields = 1000; 设置所以文件的大小总和 // 上传完成后处理 form.parse(req, (err, fields, files) => { if (err) { console.log("parse:",err); res.json(configVar.fileUp); } else { const inputFile = files.file[0]; const uploadedPath = inputFile.path var imgtype = inputFile.originalFilename; const typarr = imgtype.split("."); const typ = typarr[typarr.length -1]; const nm = new Date().getTime() + '' + Math.floor(Math.random()*1000000) ; console.log(fields.old); imgtype = nm + '.' + typ; const inPath = `./public/static/${imgtype}`; //重命名的路径 // 判断是否存在./dist/static/files文件 fs.stat('./public/static', (err, stats) => { if (JSON.stringify(stats) === undefined) { fs.mkdirSync('./public/static') } storeFiles(uploadedPath, fields, inPath) }); } }); function storeFiles(uploadedPath, fields, inPath) { //重命名为真实文件名 fs.rename(uploadedPath, inPath, (err) => { if (err) { console.log("rename:",err); res.json(configVar.rename); } else { var ret = { data:inPath.substring(8) }; Object.assign(ret , configVar.success); res.json(ret); } }); }});