@sourceloop/file-utils

中文文档
0.7.2发布于 2026/11/02MITTypeScriptCommonJS构建来源已验证

file upload and multipart related utilities for loopback4 applications

原始使用文档
文档目录9 节
  1. Installation
  2. Usage
  3. Multipart Request Decorator
  4. File Decorator
  5. File Validations
  6. ClamAV
  7. Limits Configurations
  8. Contributing
  9. License

File Utils

This package provides utilities for adding file upload and validations in LoopBack 4 microservices.

Installation

To install the package, run the following command:

npm install @sourceloop/file-utils

Usage

  • bind the component and add the require bindings.
this.bind(AWSS3Bindings.Config).to({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  region: process.env.AWS_REGION,
} as AwsS3Config);

this.component(FileUtilComponent);

You have two ways to accept multipart requests in a controller -

  • add the multipartRequestBody decorator to the controller method where you want to accept a multipart request body with/without files -
  @post(`/parents/no-model-metadata`)
  @response(200, {
    description: 'Parent without config model instance',
    content: {
      'application/json': {schema: getModelSchemaRef(ParentWithConfig)},
    },
  })
  async createWithOutModelConfig(
    @multipartRequestBody(ParentWithConfig)
    data: ParentWithModelConfig,
  ): Promise<void> {
    ...
  }

You can read more about this decorator here

  • add the file decorator to the controller method where you want the handle the file -
@file(getJsonSchema(Parent) as SchemaObject, ['file'], ['.csv'])
data: ParentWithFile,

You can read more about the file decorator and it's parameters here

Multipart Request Decorator

This decorator allows a multipart/form-data request body, with as many fields and files as we like. It requires you to define a model for request, and if any field is of file type, you need to decorate it with @fileProperty -

@model()
export class ParentWithConfig extends Entity {
  @property({
    type: 'string',
    id: true,
  })
  id?: string;

  @property({
    type: 'string',
    required: true,
  })
  name: string;

  // file field
  @fileProperty({
    type: 'object',
    // you can configure individual fields here
    validators: [FileTypeValidator],
    extensions: ['.png', '.txt'],
  })
  file: Express.Multer.File;

  constructor(data?: Partial<ParentWithConfig>) {
    super(data);
  }
}

File Decorator

This decorator is designed to handle single file uploads in a multipart/form-data request. It provides a structured way to manage multiple fields, including file fields, in your request body.

Parameters

  • schema (SchemaObject):

    • The schema object for the request body. It is useful in cases where you have multiple fields and you want to handle this data in a structured way. For example, if your request has a file field and a name field, you can define a schema object with these fields and pass it to the decorator. The file field will be marked as binary in the schema.
  • fileFields (string[]):

    • The fields in the schema that represent file uploads. So as per the above example, you can pass ['file'] to this parameter. This will mark the file field as binary in the schema.
  • allowedExtensions (string[]):

    • The allowed file extensions for the uploaded files.
  • storageOptions (IFileStorageOptions<T>):

    • The options for file storage. This supports any multer storage engine class. By default, this uses in-memory storage, and the package also provides an S3 storage engine.

S3 Storage Engine

By default, the files are stored in memory, but the package also provides an s3 based storage engine as well, to use it, you need to install the loopback4-s3 package - npm i loopback4-s3 and then you can provide it in the configuration property of the @fileProperty or @file decorators. You also need to bind it globally as follows -

import {MulterS3Storage} from '@sourceloop/file-utils/s3';
...
// inside component/application constructor
this.service(MulterS3Storage);

File Validations

The package provides two validators by default -

  • FileTypeValidator - validates the type of the file as per configurations
  • FileNameValidator - validates the name of the file, to avoid certain special characters in the name

You can write your own custom validators and register them using the @fileValidator decorator, every validator must implement the IFileValidator interface -

@fileValidator()
export class FileSizeValidator implements IFileValidator {
  ...
}

ClamAV

The package provides a validator based on ClamAV, to use it, you need to install the clamscan package - npm i clamscan and then bind the validators in your application.ts as -

this.service(ClamAVValidator);

Limits Configurations

You can configure the multer instance by binding an instance of IFileLimitsGetter on the FileUtilBindings.LimitProvider key -

this.bind(FileUtilBindings.LimitProvider).to({
  get() {
    // this is the default limits in the package
    fileSize: FIVE * MB, // 5 MB
    files: 1,
  }
});


// OR you can use a class or any other type of binding as long as it returns
// an instance of `IFileLimitsGetter-
this.bind(FileUtilBindings.LimitProvider).toClass(MulterConfigService);

You would also need to update the model decorator with following config in your model file -

@model({
  settings: {multer: {limitsProvider: true}},
})
export class TestModel extends Entity {}

Contributing

Contributions are welcome! Please refer to the contribution guidelines for more information.

License

This package is MIT licensed.

版本与发布记录

@sourceloop/file-utils 共发布 31 个版本,首次发布于 2024/08/15;过去 12 个月发布了 9 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.7.2latest2026/11/021 天前
0.7.12026/09/101 个月前
0.7.02026/08/162 个月前
0.6.02026/06/194 个月前
0.5.62026/03/097 个月前
0.5.52026/02/208 个月前

关于 @sourceloop/file-utils 的常见问题

@sourceloop/file-utils 是什么?

用于loopback应用程序的文件上传和多部分相关实用程序

如何安装 @sourceloop/file-utils?

在项目目录运行 npm install @sourceloop/file-utils,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@loopback/core(^7.0.3)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@sourceloop/file-utils 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@sourceloop/file-utils 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@sourceloop/file-utils 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js 22 || 24。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@sourceloop/file-utils 可以商用吗?

@sourceloop/file-utils 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@sourceloop/file-utils 还在维护吗?

最新版本 0.7.2 发布于 2026/11/02(1 天前);至今共发布 31 个版本,其中过去 12 个月发布了 9 个;首次发布于 2024/08/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。