Is it possible to verify a file's type with Nestjs Pipes and the FileTypeValidator?

I am facing an issue with implementing a Nestjs route in a controller that includes a file upload using Multer. The goal is to edit a user's profile picture, so I need to validate that the uploaded file is an image. However, despite using the FileTypeValidator, I am unable to get it to work properly. Every time I try to upload a file, it gets denied.

@UseInterceptors(
  FileInterceptor('file', {
    storage: MulterService.getStorage((req, file, cb) => {
      const filename = `${uuidv4()}`;
      const extension = path.parse(file.originalname).ext;

      cb(null, `${filename}${extension}`);
    }, MulterService.destinations.profilePictures),
  })
)
@Post('profile-picture')
editProfilePicture(
  @UploadedFile(
    new ParseFilePipe({
      validators: [new FileTypeValidator({ fileType: 'png' })],
      // png files always denied
      // /\^(jpeg|jpg|png|gif)$/ regex isn't working either
    })
  )
  file: Express.Multer.File
): Promise<User> {
  // ...
}

Answer №1

In case the regular expression /\.(jpg|jpeg|png)$/ doesn't work, you can try using '.(png|jpeg|jpg)'

@UploadedFile(
    new ParseFilePipe({
      validators: [
        new MaxFileSizeValidator({ maxSize: max size of file in bytes }),
        new FileTypeValidator({ fileType: '.(png|jpeg|jpg)' }),
      ],
    }),
  )
  file: Express.Multer.File

Answer №2

After testing your regex pattern, I found that it was not matching the image extensions you provided. Instead, it assumed that there would always be a dot character at the beginning. To fix this, I removed the first two characters \. from the regex and now it works perfectly. The final regex is: (jpeg|jpg|png|gif)$

Update: You can validate this using the ParseFilePipe or ParseFilePipeBuilder validation Pipeline. ParseFilePipe

@UploadedFile(
    new ParseFilePipe({
      validators: [
        new MaxFileSizeValidator({ maxSize: maximum file size in bytes }),
        new FileTypeValidator({ fileType: /\.(jpg|jpeg|png)$/ }),
      ],
    }),
  )
  file: Express.Multer.File

ParseFilePipeBuilder

@UploadedFile(
    new ParseFilePipeBuilder()
      .addFileTypeValidator({
        fileType: /\.(jpg|jpeg|png)$/,
      })
      .addMaxSizeValidator({
        maxSize: maximum file size in bytes
      })
      .build({
        // Custom Message???
        errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY
      }),
  )
  file: Express.Multer.File

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for sending information to a nested Angular 2 attribute component

As per the instructions found on this blog, in order to create inner components within an SVG using Angular 2, we need to utilize an [attribute] selector: // Within svgmap.component.ts file: component declaration @Component({ selector: '[svgmap]& ...

How can we transform the `toUSD(amount)` function into a prototype function?

This function is functioning perfectly as intended. function toUSD(amount): string { // CONVERT number to $0.00 format return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount); }; Here is how I currently i ...

An issue arises following an upgrade in Angular from version 9 to version 10, where the property 'propertyName' is being utilized before it has been initialized

I've spent time looking on Google, Github, and Stackoverflow for a solution to this error, but I'm still struggling to fix it. Can anyone offer a suggestion or help? Recently, I upgraded my Angular project from version 9 to version 10, and after ...

Exploring the power of Vue CLI service in conjunction with TypeScript

I've recently set up a Vue project using the Vue CLI, but now I am looking to incorporate TypeScript into it. While exploring options, I came across this helpful guide. However, it suggests adding a Webpack configuration and replacing vue-cli-service ...

How can parameters be implemented in Angular similar to NodeJs Express style?

Is there a way to implement a Parameter in Angular routes that resembles the NodeJs style? I have a route like **http://myhost.domain.com/signin**" and I want to pass an id for the signin request. Although I can achieve this using **http://myhost.doma ...

Unexpected INTERNAL error encountered with Firebase's Cloud Function update

Currently, I am immersed in a project involving Vue.js 3, Typescript, and Firebase. However, while attempting to integrate new cloud functions, I came across an unexpected issue: Failed to load resource: the server responded with a status of 500 () Un ...

Passing a value from an HTML template to a method within an Angular 4 component

Encountering an issue with Angular 4. HTML template markup includes a button: <td><a class="btn btn-danger" (click)="delete()"><i class="fa fa-trash"></i></a></td> Data is assigned to each td from a *ngFor, like {{ da ...

Encountering an error while testing Jasmine + Angular with Typescript: "TypeError: 'undefined' is not an object."

I'm having some difficulty while trying to test a specific service. It seems that I am struggling to match the mock response correctly: public getCustomerDetails(customerID:string): ng.IPromise<ICustomerDetails> { return this.testService.g ...

Sorting List Algorithm

Looking to create an algorithm in Node.js that abides by specific rules. It takes a series of numbers as input and the maximum consecutive number before taking a break. The logic is as follows: The rules : Only one competition per day Competitions are hel ...

Developing a collection of components with customizable color variations using React

I am interested in creating a React component library where users can specify color variants. For instance, I want to use the following syntax: const customTheme = createCustomTheme({ button: { variants: { primary: 'primary ...

The module for the class could not be identified during the ng build process when using the --

Encountering an error when running: ng build --prod However, ng build works without any issues. Despite searching for solutions on Stack Overflow, none of them resolved the problem. Error: ng build --prod Cannot determine the module for class X! ...

Converting Mesh to Object3D: A step-by-step guide

Currently utilizing Typescript alongside Webpack. To create a 3D floor using three.js, I have integrated multiple plane objects (100 in total) with a seamless image serving as their background: import { Scene, PerspectiveCamera, WebGLRenderer, ...

Customize your Loopback 4 OpenAPI with NSWAG by making filters optional and specifying data types

I am encountering an issue with the Loopback 4 filter on the generated endpoints being marked as required in my Nswag typescript file. I need it to be optional, but I am struggling to locate where this requirement is originating from. The endpoint from my ...

Setting up jsonServer in gulp with typescript: A guide

Previously, I had set up a json server and used the following code to start it: I found guidance in this GitHub repository. Starting angular2 project with gulp gulp-live-server.js var gulpCore = require('gulp'); var gulpParam = require('g ...

Keep the list up-to-date by adding new items promptly

Utilizing Angular 7, I have implemented the following service (Click here for StackBlitz Example): @Injectable({ providedIn: 'root' }) export class TodoService { todos: BehaviorSubject<Todo[]> = new BehaviorSubject([ { id: 1, tit ...

What is the appropriate typescript type for an array payload when using the fetch API?

My current method involves using fetch to send URL encoded form data: private purchase = async () => { const { token } = await this.state.instance.requestPaymentMethod(); const formData = []; formData.push(`${encodeURIComponent("paymentTok ...

Mastering the utilization of API routes within the Next JS 13 App Router framework

As a newcomer to React JS and Next.js, I recently made the switch from using the Page Router API in Next.js to utilizing the new App Router introduced in Next.js 13. Previously, with the Page Router, creating a single GET request involved nesting your "JS ...

What is the best way to implement multiple ternary operators within HTML code?

Consider the following code snippet: It currently applies CSS classes up to red4, but I want to apply CSS classes up to red11. Additionally, the variable "size" in myData should be dynamic. For example, size could range from 0-20 // 0-100 // 0-10000, etc., ...

Is there a way to append a unique property with varying values to an array of objects in TypeScript?

For instance: items: object[] = [ {name: 'Backpack', weight: 2.5}, {name: 'Flashlight', weight: 0.8}, {name: 'Map', weight: 0.3} ]; I prefer the items to have an 'age' property as well: it ...

Select numerous files and conveniently delete them using the angular delete button

Background: In one of my tables, there is a column where users can either choose or upload files as input. I have implemented a feature that allows users to select multiple files at once. Issue at Hand: What I am trying to achieve is to have an 'x&ap ...