javascriptnode.jstypescriptnestjsmultipartform-data

Request body of multiple file uploads in multipart formdata with unique metadata


I'm working on a NestJS app and in it, one route has file uploading in it. I am uploading the file and its metadata using form-data. Right now, I am able to upload just one file at a time and the form-data looks like this:

Key      Type     Value
file     File     some_file.pdf
name     Text     File Name
type     Text     document
category Text     profile

and so on and so forth.

My DTO looks like this:

export class UploadFileDto {
    @IsString()
    @Length(2, 255)
    name: string;
    @IsString()
    type: string;
    @IsString()
    category: string;
    @IsOptional()
    force: string = 'false';
}

This works fine for just one file. My question now is that I want to be able to upload multiple files and all of those files would have their unique metadata. How can I do this and how can I structure my form-data to handle this?


Solution

  • You can send multiple sets of file + metadata by using an array format in your form-data keys like files[0].file, files[0].name, files[1].file, etc., and update your DTO to handle an array of file metadata objects. Then, in your controller, use @Body() for metadata and @UploadedFiles() with @UseInterceptors(FilesInterceptor(...)) for files.