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

執行此程式碼後,您將獲得以下表單。

File Upload Form

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

File Console Screen

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

廣告