找了不少檔案上傳的相關模組,最後選了比較常用、也是 express 推薦使用的 multer 來實作檔案上傳,附上 GitHub 位址。
1. 開始
第一步自然是安裝模組:
npm install multer --save
這裡簡單說明一下:檔案上傳是用 POST 方法提交資料,所以上傳的單檔或多檔會作為一個 body 附加到請求物件中,我們可以透過 req.file 或 req.files 查看上傳後檔案的相關資訊。
以單檔上傳為例,req.file 回傳一個物件:
{ "fieldname":"avatar", #前端上傳文件input的name "originalname":"Wx.php", #本地文件名 "encoding":"7bit", #文件編碼類型 "mimetype":"text/php", #文件類型 "destination":"uploads/", #上傳根目錄 "filename":"1497286037422Wx.php", #上傳後文件名 "path":"uploads/1497286037422Wx.php", #文件路徑 "size":18174 #文件大小 }
這個物件的 key 是固定的,value 則依配置產生,可用來實作相關邏輯。
2. 實作
實作分為前端和後端兩部分。
前端
前端就是普通的寫法,用 form 表單提交:
<form action="/test/upload" method="post" enctype="multipart/form-data"> <input type="file" name="avatar"> <input type="submit" name="提交"> </form>
切記,enctype="multipart/form-data" 這個屬性一定要加上,否則後端接收不到檔案。
後端
首先我們新建配置檔 upload.js:
// upload.js var multer = require('multer'); # 引入模塊 var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/') }, filename: function (req, file, cb) { cb(null, Date.now()+file.originalname) } }) var upload = multer({ storage: storage }) module.exports = upload;
diskStorage 方法相當於建立一個磁碟存儲引擎,用來配置上傳路徑、檔名等,可控性更高:
destination # 設置文件上傳路徑 filename # 重命名文件
接著新建路由來接收檔案 file.js:
// file.js var express = require('express'); var router = express.Router(); // 引入配置文件 var upload = require('../config/upload'); router.post('/upload', upload.single('avatar'), function(req, res, next) { res.send(req.file); }); module.exports = router;
file.js 中的 upload.single() 表示接收單檔,常用的還有:
upload.single(fname); // 接收單文件 upload.array(fname[, maxCount]) //接收多文件,maxCount表示接收最大數量
其中 fname 是前端 <input type="file" name="fname"> 的 name 值。
基本的檔案上傳方法就是這些。當然還有許多配置參數之類的設定,需要參考 GitHub 說明,位址在開頭,需要的朋友可自行查閱。