Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTF-8 encoding with FilesInterceptor from NestJS

I'm using @FilesInterceptor and @UploadedFiles from NestJS to upload files in my API. Here's part of the code :

  @HttpCode(200)
  @UseInterceptors(
    FilesInterceptor('files', undefined, {
      preservePath: true,
      limits: {
        fileSize: process.env.FILES_STORAGE_SIZE
          ? parseInt(process.env.FILES_STORAGE_SIZE)
          : 1073741824, // 1GB
      },
    }),
  )
  async uploadFiles(
    @UploadedFiles() files: Express.Multer.File[],
    @UserReq('id') userId: number,
    @Param('parentId') parentId: string | null,
  )

The problem I encounter is that the file.originalname is not correctly encoded. If the file is named "Tést.pdf", I get "teÌst.pdf". I cannot find which parameter to set to fix the issue

One solution is to convert the file name after the upload

const fileNameEncoded = Buffer.from(file.originalname, 'latin1').toString(
    'utf8',
);

But I would prefer using Multer options to fix the issue

Thanks for the help

like image 383
Kokno Avatar asked Sep 12 '25 03:09

Kokno


1 Answers

To solve this issue in your NestJS app, you can provide MulterModule with a fileFilter defined as follow:

MulterModule.register({
  fileFilter: (_, file, cb) => {
    file.originalname = Buffer.from(file.originalname, 'latin1').toString('utf8');
    cb(null, true);
  },
}),

This will apply the workaround for every controllers in your app.

like image 166
L. Gregoire Avatar answered Sep 13 '25 17:09

L. Gregoire