为了账号安全,请及时绑定邮箱和手机立即绑定

koa2实现文件上传

标签:
Node.js

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

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消