上传文件使用 formidable-upload-koa 模块
下载文件使用 koa-send 模块
router
const router = require('koa-router')()
const koaForm = require('formidable-upload-koa')
const { saveFile } = require('../controller/files')
const send = require('koa-send')
const path = require('path')
const options = {
uploadDir: `${__dirname}/`,
keepExtensions: true,
maxFileSize: 1024 * 1024
}
router.post('/upload', koaForm(options), async (ctx, next) => {
const file = ctx.req.files['file']
const { size, path, name, type } = file
ctx.body = await saveFile({
name,
type,
size,
filePath: path
})
})
router.get('/download', async (ctx, next) => {
const fileName = ctx.query.filename
const dir = path.join(__dirname, '..', 'uploadFiles')
ctx.attachment(fileName)
try {
await send(ctx, fileName, { root: dir})
} catch (e) {
ctx.throw(404, '文件不存在')
}
})
module.exports = router
controller
const fse = require('fs-extra')
const path = require('path')
const MIX_SIZE = 1024 * 1024 * 1024
async function saveFile({ name, type, size, filePath }) {
if (size > MIX_SIZE) {
await fse.remove(filePath)
return Promise.reject('文件体积过大')
}
const fileName = Date.now() + '.' + name
const DIST_FOLDER_PATH = path.join(__dirname, '..', 'uploadFiles')
const distFilePath = path.join(DIST_FOLDER_PATH, fileName)
await fse.move(filePath, distFilePath)
return Promise.resolve({
url: `http://127.0.0.1:3000/${fileName}`
})
}
module.exports = {
saveFile
}
在app.js将uploadFiles设置为静态资源目录
