koa-body上傳檔案學習筆記
阿新 • • 發佈:2019-04-08
專案結構
package.json
{ "name": "koa-upload", "version": "1.0.0", "dependencies": { "koa": "^2.7.0", "koa-body": "^4.1.0", "koa-router": "^7.4.0", "nunjucks": "^3.2.0" } }
app.js
const Koa = require('koa'); const koaBody = require('koa-body'); const router = require('koa-router')(); const fs = require('fs'); const path = require('path'); const nunjucks = require('nunjucks'); const templating = require('./templating'); const controller = require('./controller'); const app = new Koa(); const isProduction = process.env.NODE_ENV === 'production'; app.use(async(ctx, next) => { console.log(`Process ${ctx.request.method} ${ctx.request.url}...`); var start = new Date().getTime(), execTime; await next(); execTime = new Date().getTime() - start; ctx.response.set('X-Response-Time', `${execTime}ms`); }); app.use(koaBody({ multipart: true, formidable: { // uploadDir: path.join(__dirname, 'upload'),<--如果配置了此處點選上傳按鈕會直接上傳,就無法在後端上傳程式碼處進行資料處理 maxFieldsSize: 200 * 1024 * 1024, } })); app.use(router.routes()); app.use(templating('views', { noCache: !isProduction, watch: !isProduction })); app.use(controller()); app.listen(3001, () => { console.log("app started at 3001..."); });
controllers/index.js
const fs = require('fs'); module.exports = { 'GET /': async(ctx, next) => { ctx.render('index.html'); }, 'POST /upload': async(ctx, next) => { //如果在app.js裡面配置了uploadDir就會上傳多上傳一遍 const file = ctx.request.files.file; const reader = fs.createReadStream(file.path); const ext = file.name.split('.').pop(); const upStream = fs.createWriteStream(`upload/${Math.random().toString()}.${ext}`); reader.pipe(upStream); //ctx.body = JSON.stringify(ctx.request.files); return ctx.body = "Upload Success"; } };
controller.js和templating.js參考廖雪