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
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}
})
