当前位置 : 主页 > 网络编程 > JavaScript >

koa2上传下载.ts

来源:互联网 收集:自由互联 发布时间:2021-06-28
koa2上传下载.ts import * as fs from 'fs'import * as multer from 'koa-multer'import * as Router from 'koa-router'// import * as lowdb from 'lowdb'const uploader = multer({ dest: 'uploads/' })const router = new Router()router.get('/attach
koa2上传下载.ts
import * as fs from 'fs'
import * as multer from 'koa-multer'
import * as Router from 'koa-router'
// import * as lowdb from 'lowdb'

const uploader = multer({ dest: 'uploads/' })
const router = new Router()


router.get('/attachments/:id', async (ctx) => {
  const { id } = ctx.params
  const info = ctx.db.get('attachments').find({ id }).value()
  
  ctx.set('Content-Disposition', `attachment; filename=${info.originalname}`)
  ctx.set('Content-Type', info.mimetype)
  ctx.set('Content-Length', info.size)
  ctx.body = fs.createReadStream(`uploads/${id}`)
})

router.post('/upload', uploader.single('file'), async (ctx) => {
  const info = Object.assign({}, ctx.req.file, { id: ctx.req.file.filename })
  await ctx.db.get('attachments').push(info).write()
  ctx.body = {ok: true, attachment: info}
})
网友评论