在node中,multer是一個用于處理“multipart/form-data”類型數(shù)據(jù)格式的中間件,主要用于上傳文件;該中間件在解析完請求體后,會向Request對象中添加一個body對象和一個file或files對象。
本文操作環(huán)境:Windows10系統(tǒng)、nodejs 12.19.0版、Dell G3電腦。
node中multer是什么意思
Multer 是一個 node.js 中間件,用于處理 multipart/form-data 類型的表單數(shù)據(jù),它主要用于上傳文件。它是寫在 busboy 之上非常高效。
注意: Multer 不會處理任何非 multipart/form-data 類型的表單數(shù)據(jù)
Multer在解析完請求體后,會向Request對象中添加一個body對象和一個file或files對象(上傳多個文件時使用files對象 )。
其中,body對象中包含所提交表單中的文本字段(如果有),而file(或files)對象中包含通過表單上傳的文件。
Tips:multipart/form-data是用來指定傳輸數(shù)據(jù)的特殊類型的,主要就是我們上傳的非文本的內容,比如圖片或者mp3等等
const express = require('express') const multer = require('multer') const app = express() const storage = multer.diskStorage({ //保存路徑 destination: function (req, file, cb) { cb(null, '/tmp/my-uploads') //注意這里的文件路徑,不是相對路徑,直接填寫從項目根路徑開始寫就行了 }, //保存在 destination 中的文件名 filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now()) } }) const upload = multer({ storage: storage }) app.post('/profile', upload.single('avatar'), function (req, res, next) { // req.file 是 `avatar` 文件的信息 // req.body 將具有文本域數(shù)據(jù),如果存在的話 }) app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) { // req.files 是 `photos` 文件數(shù)組的信息 // req.body 將具有文本域數(shù)據(jù),如果存在的話 }) const cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]) app.post('/cool-profile', cpUpload, function (req, res, next) { // req.files 是一個對象 (String -> Array) 鍵是文件名,值是文件數(shù)組 // 例如: // req.files['avatar'][0] -> File // req.files['gallery'] -> Array // req.body 將具有文本域數(shù)據(jù),如果存在的話 })
multer(options)
Multer 接受一個 options 對象,其中最基本的是 dest 屬性,這將告訴 Multer 將上傳文件保存在哪。如果你省略 options 對象,這些文件將保存在內存中,永遠不會寫入磁盤。
通常,一般的網頁應用,只需要設置 dest 屬性,像這樣:
const upload = multer({ dest: 'uploads/' })
如果你想在上傳時進行