
- Koa.js 教程
- Koa.js - 主頁
- Koa.js - 概述
- Koa.js - 環境
- Koa.js - Hello World
- Koa.js - 生成器
- Koa.js - 路由
- Koa.js - URL 構建
- Koa.js - HTTP 方法
- Koa.js - 請求物件
- Koa.js - 響應物件
- Koa.js - 重定向
- Koa.js - 錯誤處理
- Koa.js - 級聯
- Koa.js - 模板
- Koa.js - 表單資料
- Koa.js - 檔案上傳
- Koa.js - 靜態檔案
- Koa.js - Cookie
- Koa.js - 會話
- Koa.js - 認證
- Koa.js - 壓縮
- Koa.js - 快取
- Koa.js - 資料庫
- Koa.js - RESTful API
- Koa.js - 日誌記錄
- Koa.js - 腳手架
- Koa.js - 資源
- Koa.js 實用資源
- Koa.js - 快速指南
- Koa.js - 實用資源
- Koa.js - 討論
Koa.js - 檔案上傳
Web 應用程式需要提供允許檔案上傳的功能。讓我們看看如何從客戶端接收檔案並將它們儲存在我們的伺服器上。
我們已經使用了 koa-body 中介軟體來解析請求。此中介軟體還用於處理檔案上傳。讓我們建立一個表單,允許我們上傳檔案,然後使用 Koa 儲存這些檔案。首先建立一個名為 file_upload.pug 的模板,其中包含以下內容。
html head title File uploads body form(action = "/upload" method = "POST" enctype = "multipart/form-data") div input(type = "text" name = "name" placeholder = "Name") div input(type = "file" name = "image") div input(type = "submit")
請注意,您需要在表單中提供與上述相同的編碼型別。現在讓我們在我們的伺服器上處理此資料。
var koa = require('koa'); var router = require('koa-router'); var bodyParser = require('koa-body'); var app = koa(); //Set up Pug var Pug = require('koa-pug'); var pug = new Pug({ viewPath: './views', basedir: './views', app: app }); //Set up body parsing middleware app.use(bodyParser({ formidable:{uploadDir: './uploads'}, //This is where the files would come multipart: true, urlencoded: true })); var _ = router(); //Instantiate the router _.get('/files', renderForm); _.post('/upload', handleForm); function * renderForm(){ this.render('file_upload'); } function *handleForm(){ console.log("Files: ", this.request.body.files); console.log("Fields: ", this.request.body.fields); this.body = "Received your data!"; //This is where the parsed request is stored } app.use(_.routes()); app.listen(3000);
執行此程式碼後,您將獲得以下表單。

提交後,您的控制檯將生成以下輸出。

上傳的檔案儲存在上述輸出中的路徑中。您可以使用 this.request.body.files 訪問請求中的檔案,並使用 this.request.body.fields 訪問該請求中的欄位。
廣告