Try   HackMD

🏅 Day 32 - multer 處理上傳檔案

Multer 為一個 node.js middleware,處理 multipart/form-data 資料,主要用於上傳檔案。
使用者上傳圖片 POST 請求,檔案會以 form data 的形式傳送到後端,因此會使用到 multer() 處理接收到的資料。
multer() 可以加入 options 設定,這裡主要會加入 fileFilterlimits 限制上傳圖片檔案類型以及最大檔案容量。

範例:
routes/upload.js

const multer = require('multer'); const path = require('path'); const upload = multer({ limits: { fileSize: 2 * 1024 * 1024, }, fileFilter (req, file, cb) { // path.extname() 取得副檔名(如 .jpg) const ext = path.extname(file.originalname).toLowerCase(); // 如果不是 .jpg, .png, .jpeg 就拒絕上傳檔案 if (ext !== '.jpg' && ext !== '.png' && ext !== '.jpeg') { cb('檔案格式錯誤,僅限上傳 jpg、jpeg 與 png 格式。'); } // 接受檔案 cb(null, true); }, }).any();

題目

練習運用上方範例,帶入上傳圖片路由 POST /upload,使用 multer 套件處理 form-data,若有上傳圖片成功則回傳成功訊息 status: 'success'

完整下方程式碼 ... 的部分

app.js

const uploadRouter = require('./routes/upload'); app.use('/upload', uploadRouter);

routes/upload.js

const multer = require('multer'); const path = require('path'); const upload = multer({ ... }).any(); router.post('...', (req, res) => { upload(req, res, () => { res.send({ ... }) }) })

參考資源

回報流程

將答案寫在 CodePen 並複製 CodePen 連結貼至底下回報就算完成了喔!
解答位置請參考下圖(需打開程式碼的部分觀看)

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

回報區

Discord CodePen / 答案
xxx CodePen
苡安 hackmd
Chia Pin CodePen
wei CodePen
Hank CodePen
william威良 CodePen
jenny7532 CodePen
Lobinda HackMD
runweiting CodePen
mei CodePen
fabio20 CodePen