package.json 文件node
{ "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "dependencies": { "formidable": "^1.2.1", "koa": "^2.5.1", "koa-body": "^2.6.0", "koa-logger": "^3.2.0", "koa-router": "^7.4.0", "koa-static-cache": "^5.1.2" }, "devDependencies": {}, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" }
const Koa = require('koa') const logger = require('koa-logger') const router = require('koa-router')() const formidable = require('formidable') const koaBody = require('koa-body') const util = require('util') const path = require('path') const staticCache = require('koa-static-cache') const fs = require('fs') const app = new Koa() const port = 8080 app.use(logger()) // 輸出日誌 app.use(koaBody()) // body 解析 // 設置img 目錄爲靜態資源 app.use(staticCache(path.join(__dirname, 'img'), { maxAge: 365 * 24 * 60 * 60, gzip: true, buffer: true, dynamic: true })) router // 首頁 .get('/', ctx => { ctx.body = '<form action="/upload" enctype="multipart/form-data" method="post">' + '<input type="text" name="title"><br>' + '<input type="file" name="upload" multiple="multiple"><br>' + '<input type="submit" value="Upload">' + '</form>' }) // 上傳文件接口 .post('/upload', async ctx => { const form = new formidable.IncomingForm() // 設置存儲文件的目錄 const imgPath = path.join(__dirname, '/img') // 若是目錄不存在則建立 if (!fs.existsSync(imgPath)) fs.mkdirSync(imgPath) form.uploadDir = imgPath // 上傳文件大小限制 form.maxFieldsSize = 20 * 1024 * 1024 let result = await new Promise(r => { form.parse(ctx.req, function (err, fields, files) { if (err) { r({ err }) } else { // 手動給文件加後綴, formidable默認保存的文件是無後綴的 let newPath = files.upload.path + '_' + files.upload.name fs.renameSync(files.upload.path, newPath) r({ path: newPath }) } }) }) const basename = '/' + path.basename(result.path) if (result.err) ctx.throw(400, '異常錯誤') else ctx.body = `<p>url: ${basename}</p><img src=${basename} style="max-width: 100%;">` }) app.use(router.routes()) app.on('error', (err, ctx) => { log.error('server error', err, ctx) }) app.listen(port, () => { console.log('listen ', port) })
node .