继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

koa2实现文件上传

慕粉0851399811
关注TA
已关注
手记 1
粉丝 0
获赞 0

app.js

const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const index = require('./routes/index')
const cascader = require('./routes/cascader')
const tree = require('./routes/tree')
const upload = require('./routes/upload')
const users = require('./routes/users')
const pdf = require('./routes/pdf')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  if (ctx.method == 'OPTIONS') {
    ctx.status = 200
  } else {
    await next();
  }
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(cascader.routes(), cascader.allowedMethods())
app.use(tree.routes(), tree.allowedMethods())
app.use(upload.routes(), upload.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(pdf.routes(), pdf.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app

upload.js

const router = require('koa-router')()
const multer = require('koa-multer')

const storage = multer.diskStorage({
  // 文件保存路径,注意windows和linux系统存储路径写法区别,否则会报404错误
  destination: function (req, file, cb) {
    cb(null, 'public/uploads/')//path.resolve('public/uploads') // windows
    // cb(null, '/usr/local/themesui-server/public/uploads') // linux
  },
  //修改文件名称
  filename: function (req, file, cb) {
    const fileFormat = (file.originalname).split(".");  //以点分割成数组,数组的最后一项就是后缀名
    cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
  }
})
//加载配置
const upload = multer({
  storage: storage,
  limits: {
    // fileSize: 1024 * 1024 / 2 // 限制512KB
    fileSize: 1024 * 1024 * 20 // 限制15M
  }
});

router.prefix('/themesui/upload')

router.post('/', upload.single('file'), async (ctx, next) => {
  // 返回原文件名
  let name = ctx.req.file.originalname
  let url = `/uploads/${ctx.req.file.filename}`
  ctx.body = {
    code:200,
    name,
    url,
    userInfo: ctx.req.body
  }
})

module.exports = router

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP