這個包其實是著名的 ExpressJS multer v2.0.0-rc.4 原生包的一個分支。主要對於那些喜歡 Promise 風格程式設計而不是中間件的開發人員來說會很有趣。此外,同樣重要的是,這個套件是用 TypeScript 編寫的,因此其中的類型支援和上下文文件都是一流的。
確保您已安裝 Node.js >= v20.0.6。可以使用以下命令安裝該軟體包:
npm install @ts-stack/multer
Multer 傳回一個具有四個屬性的物件:formFields、file、files 和 groups。 formFields 物件包含表單文字欄位的值,file、files 或 groups 物件包含透過表單上傳的檔案(作為可讀流)。
以下範例僅為了簡單起見而使用 ExpressJS。事實上,@ts-stack/multer 不傳回中間件,因此對於 ExpressJS 來說不如原始模組方便。基本用法範例:
import { Multer } from '@ts-stack/multer'; import express from 'express'; import { createWriteStream } from 'node:fs'; // Here `avatar`, `photos` and `gallery` - is the names of the field in the HTML form. const multer = new Multer({ limits: { fileSize: '10MB' } }); const parseAvatar = multer.single('avatar'); const parsePhotos = multer.array('photos', 12); const parseGroups = multer.groups([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]); const app = express(); app.post('/profile', async (req, res, next) => { const parsedForm = await parseAvatar(req, req.headers); // parsedForm.file is the `avatar` file // parsedForm.formFields will hold the text fields, if there were any const path = `uploaded-files/${parsedForm.file.originalName}`; const writableStream = createWriteStream(path); parsedForm.file.stream.pipe(writableStream); // ... }); app.post('/photos/upload', async (req, res, next) => { const parsedForm = await parsePhotos(req, req.headers); // parsedForm.files is array of `photos` files // parsedForm.formFields will contain the text fields, if there were any const promises: Promise<void>[] = []; parsedForm.files.forEach((file) => { const promise = new Promise<void>((resolve, reject) => { const path = `uploaded-files/${file.originalName}`; const writableStream = createWriteStream(path); file.stream.pipe(writableStream); writableStream.on('finish', resolve); writableStream.on('error', reject); }); promises.push(promise); }); await Promise.all(promises); // ... }); app.post('/cool-profile', async (req, res, next) => { const parsedForm = await parseGroups(req, req.headers); // parsedForm.groups is an object (String -> Array) where fieldname is the key, and the value is array of files // // e.g. // parsedForm.groups['avatar'][0] -> File // parsedForm.groups['gallery'] -> Array // // parsedForm.formFields will contain the text fields, if there were any });
如果您需要處理純文字的多部分錶單,可以使用 .none() 方法,例如:
import { Multer } from '@ts-stack/multer'; import express from 'express'; const parseFormFields = new Multer().none(); const app = express(); app.post('/profile', async (req, res, next) => { const parsedForm = await parseFormFields(req, req.headers); // parsedForm.formFields contains the text fields });
這是錯誤代碼清單:
const errorMessages = new Map<ErrorMessageCode, string>([ ['CLIENT_ABORTED', 'Client aborted'], ['LIMIT_FILE_SIZE', 'File too large'], ['LIMIT_FILE_COUNT', 'Too many files'], ['LIMIT_FIELD_KEY', 'Field name too long'], ['LIMIT_FIELD_VALUE', 'Field value too long'], ['LIMIT_FIELD_COUNT', 'Too many fields'], ['LIMIT_UNEXPECTED_FILE', 'Unexpected file field'], ]);
您可以在 MulterError#code 屬性中看到這些錯誤代碼:
import { Multer, MulterError, ErrorMessageCode } from '@ts-stack/multer'; // ... try { const multer = new Multer().single('avatar'); const parsedForm = await multer(req, req.headers); // ... } catch (err) { if (err instanceof MulterError) { err.code // This property is of type ErrorMessageCode. // ... } }
以上是@ts-stack/multer 簡化了將檔案上傳到基於 Node.js 的後端的詳細內容。更多資訊請關注PHP中文網其他相關文章!