@ts-stack/multer 简化了将文件上传到基于 Nodejs 的后端
文章标签
文件上传
这个包实际上是著名的 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 对象包含表单文本字段的值,文件、文件或组对象包含通过表单上传的文件(作为可读流)。
以下示例使用 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});</void></void>
如果您需要处理纯文本的多部分表单,可以使用 .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'],]);</errormessagecode>
您可以在 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. // ... }}