首頁  >  文章  >  web前端  >  @ts-stack/multer 簡化了將檔案上傳到基於 Node.js 的後端

@ts-stack/multer 簡化了將檔案上傳到基於 Node.js 的後端

WBOY
WBOY原創
2024-07-29 15:31:24791瀏覽

@ts-stack/multer simplifies uploading files to a Node.js-based backend

這個包其實是著名的 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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn