Koa2使用koa-body实现文件上传(Node可读流可写流) 发表于 2018-03-27 koa-body文件上传自定义文件夹及文件名称123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119const Koa = require('koa'), //bodyParser = require('koa-bodyparser'), router = require('koa-router')(), stc = require('koa-static'), render = require('koa-art-template'), fs = require('fs'), path = require('path');const koaBody = require('koa-body');//引入子模块var admin = require('./routes/admin.js');var api = require('./routes/api.js');var index = require('./routes/index.js');var app = new Koa();//配置koa-art-template 模板引擎render(app, { root: path.join(__dirname, 'views'), extname: '.html', debug: process.env.NODE_ENV !== 'production', minimize: true, htmlMinifierOptions: { collapseWhitespace: true, minifyCSS: true, minifyJS: true, // automatically merged at runtime: rules.map(rule => rule.test) ignoreCustomFragments: [] }});//app.use(bodyParser());app.use(stc( path.join(__dirname, './statics')))app.use(stc( path.join(__dirname, './public')))//koaBodyapp.use(koaBody({ multipart: true, // 支持文件上传 encoding: 'gzip', formidable: { uploadDir: path.join(__dirname, 'public/upload/'), // 设置文件上传目录 keepExtensions: true, // 保持文件的后缀 maxFieldsSize: 2 * 1024 * 1024, // 文件上传大小 onFileBegin: (name, file) => { // 文件上传前的设置 // console.log(`name: ${name}`); // console.log(file); }, }}));//配置路由router.use(index);/* /admin 配置子路由 层级路由 /admin/user */router.use('/admin', admin);/* /api/newslist 新闻列表的api */router.use('/api', api); /*在模块里面暴露路由并且启动路由*/router.post('/getData', async(ctx, next) => { let request = ctx.request; let req_query = request.query; let req_querystring = request.querystring; console.log(request, req_query, req_querystring); console.log(ctx.request.body) console.log(ctx.request.files); ctx.cookies.set( 'MyName', 'Koa2', { domain: '127.0.0.1', // 写cookie所在的域名 path: '/', // 写cookie所在的路径 maxAge: 1000 * 60 * 60 * 24, // cookie有效时长 expires: new Date('2018-12-31'), // cookie失效时间 httpOnly: false, // 是否只用于http请求中获取 overwrite: false // 是否允许重写 } ); //ctx.status = 200 return ctx.body = { code: 200, data: { arr: [1, 2, 3, 4] } };})router.post('/uploadPic', async(ctx, next) => { const file = ctx.request.files.file; // 上传的文件在ctx.request.files.file // 创建可读流 const reader = fs.createReadStream(file.path); // 修改文件的名称 var myDate = new Date(); var newFilename = file.name.split('.')[0] + '_' + myDate.getTime() + '.' + file.name.split('.')[1]; var targetPath = path.join(__dirname, './public/upload/') + `/${newFilename}`; //创建可写流 const upStream = fs.createWriteStream(targetPath); // 可读流通过管道写入可写流 reader.pipe(upStream); //ctx.redirect('/') //返回保存的路径 return ctx.body = { code: 200, data: { url: 'http://' + ctx.headers.host + '/upload/' + newFilename } };});//启动路由app.use(router.routes()).use(router.allowedMethods());app.listen(12300);