首页  >  文章  >  web前端  >  @ts-stack/multer 简化了将文件上传到基于 Node.js 的后端

@ts-stack/multer 简化了将文件上传到基于 Node.js 的后端

WBOY
WBOY原创
2024-07-29 15:31:24676浏览

@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