简体   繁体   中英

File field is not being included in @Body decorator in NestJS

I'm trying to build a simple route where the user will post few text data along with a file. Let's say a task where the properties will be title, description, and file. I have created a DTO for this as follows:-

export class CreateTaskDto {
  title: string;
  description: string;
  file: any
}

And here is the storage.config.ts

export const storage = diskStorage({
  destination: "./uploads",
  filename: (req, file, callback) => {
    callback(null, generateFilename(file));
  }
});

function generateFilename(file) {
  const filename = file.originalname
  const ext = filename.split(".").pop()
  return `${Date.now()}_${filename}`;
}

The tasks.controller.ts

@Post()
@UseInterceptors( FileInterceptor( "file", { storage }))
async createNewTask(@UploadedFile() file, @Body() dto: CreateTaskDto) {
  /*
   here is the dto I received:
   {
      "title": "Task Title",
      "description": "Task Description"
   }

   You can see that the file field is not being added to the dto
   */
}

The file field data is not included in the @Body decorator variable dto . I know I can access the file data via the file variable but is there any way to instruct nest to include the file value into the @Body decorator?

Thanks

This is how multer works, it takes the uploaded files and attaches them to req.file or req.files depending on if one or many were sent. You could create a custom decorator to merge the req.body and req.file together if you wanted, but generally this isn't something Nest does, but the underlying package itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM