How to handle multiple formData input in NestJS controller

How can I create a controller in Nest.js that accepts two form-data inputs?

Here is my Angular service code:

public importSchema(file: File, importConfig: PreviewImportConfig): Observable<HttpEvent<SchemaParseResponse>> {
    const formData = new FormData();
    formData.append('importConfig', new Blob([JSON.stringify(importConfig)], { type: 'application/json' }));
    formData.append('file', file);

    const req = new HttpRequest('POST', url, formData, {
      reportProgress: true,
      responseType: 'json',
    });
    return this.http.request<SchemaParseResponse>(req);
  }
}

And here is the controller code to handle the incoming request:

@Post('/import-schema')
  @UseInterceptors(FileInterceptor('file'))
  @UseInterceptors(FileInterceptor('importConfig'))
  previewFile(@UploadedFile() file: any, @Body() importConfig: PreviewImportConfig) {
    console.log("File" + file);
    return this.schemaUploadService.createPreviewImportWarnResponse();
  }

However, I am receiving a Bad Request error.

This is how the payload appears:

------WebKitFormBoundarywAJpjN6KXywEIYis
Content-Disposition: form-data; name="importConfig"; filename="blob"
Content-Type: application/json

{"preview":true,"defaults":{"include":false},"typeConfigs":{}}
------WebKitFormBoundarywAJpjN6KXywEIYis
Content-Disposition: form-data; name="file"; filename="TD_USA_Import_2_warning.xsd"
Content-Type: application/octet-stream


------WebKitFormBoundarywAJpjN6KXywEIYis--

Answer №1

To handle multiple fields within multiple fields, consider utilizing the FileFieldsInterceptor in the following manner:

@Post('/import-data')
@UseInterceptors(FileFieldsInterceptor([
  { name: 'dataConfig', maxCount: 1 },
  { name: 'dataFile', maxCount: 1 }
]))
previewData(@UploadedFiles() files: any[], @Body() dataConfig: PreviewDataConfig) {
  console.log("Uploaded Files: " + files);
  return this.dataUploadService.createPreviewDataResponse();
}

If you do not need to save the dataConfig "file", consider sending it as a stringified JSON directly in the request body instead of using new Blob, which may suit your requirements better.

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

Triggering the 'change' event on a hidden value in jQuery can cause issues with knockout dependent observables

Let me share the story of how we stumbled upon this issue... Basically, we were invoking trigger('change') on all our form inputs to notify other knockout observables that their values had been reset. However, we suspect it could be a bug in Knoc ...

What's the best way to use JavaScript to obtain the width of a 'css-pixel' based on a media query?

While there have been discussions on how to determine device sizes using media queries like Twitter Bootstrap, I am looking for a reliable way to achieve the same output using JavaScript. Specifically, I want to get the CSS media query pixel number rather ...

Django issue: A Tuple or struct_time argument is necessary

Currently, I am developing a code that deals with 2 variables - showdate and viewtype. Both of these variables are transferred via JavaScript using the POST method. viewtype = send an srt showdate = send a date from javascript Within this code snippet, ...

cookies cannot be obtained from ExecutionContext

I've been trying to obtain a cookie while working with the nestjs and graphql technologies. However, I encountered an issue when it came to validating the cookies by implementing graphql on the module and creating a UseGuard. It was suggested that I ...

Choosing from a variety of tr elements

I'm working with a table in HTML that has about 100 rows. I would like to apply different colors to specific groups of rows, such as making rows 1-10 red and rows 20-40 blue. Using nth-child seems like an option, but it can get quite verbose if I nee ...

Enhancing the type safety of TypeScript Generics

Uncertainty looms over me - am I committing an error, or is this all part of the plan... Within my academic domain class Collection<E> { ... } Lies a function public Insert(item: E): void { ... } I construct a specific instance of my list const ...

Function being called by Intersection Observer at an inappropriate moment

After running the page, the intersection observer behaves exactly as desired. However, upon reloading the page, I am automatically taken back to the top of the page (which is expected). Strangely though, when the viewport interacts with the target elemen ...

leveraging a callback function alongside the useState hook

I'm facing an issue with the change() function. My goal is to call the filteredData() function after the setState operation is completed. Typically, I would use a callback function for this task, but useState doesn't support callbacks. Using useE ...

Using Observables for Polling in Angular 8

Greetings, I am in the process of upgrading my project from Angular 5 to Angular 8. Below is the code snippet I used for polling: Observable.interval(this.intervalTime).timeout(600000) .takeWhile(() => this.alive) .subs ...

Issue with RegisterClientScriptCode function following a partial postback

In a SharePoint website, the code below is contained within a user control: ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "jquery144", "<script type=\"text/javascript\" src=\"/_layouts/Unicre.Web.RUOnline.Controlos/Script ...

Is it possible to activate events on select tags even when they have the disabled attribute?

All the select options on this page have been disabled with an ID that ends in _test, and everything seems to be functioning properly. However, I would like to display a title when the selects are disabled and the mouse hovers over them. The issue arises ...

The array.slice() method fails to work properly when I try to start it from any index other than 0

I am currently working with an array called $scope.results which contains 8 objects. I have also created a custom simple pagination and a function called selectAll() that I'm trying to get to work together. Please refrain from suggesting the use of b ...

Achieving a smooth sliding motion with the help of jQuery animation

Here is the code snippet: In HTML: <div> <div id="div1">12345</div> <div id="div2">67890</div> <div id="div3"><a href="#" id="slide">abcde</a></div> <div id="pad" style="display:non ...

Adding and removing attributes with Jquery upon clicking a button

How can I make my listed items add an ID when clicked, or what am I doing incorrectly? $('.ex-menuLi #tt').attr('id', 'test'); $('.ex-menuLi').on('click', function(){ $(this).attr('id', &apos ...

Ways to identify whether a div is in view and includes an input field

This is a unique question that is not related to the issue of querySelectorAll detecting value in input. Instead of asking whether an input field has a value, I am interested in how to detect if the current visible div contains an input field. This is a n ...

Tips for concealing dynamically generated div elements within a VueJS v-for loop

Is there a way to hide dynamically generated div elements in VueJS? In my chatbot application, messages are passed through a prop called messages. These message arrays create multiple Divs on the screen displaying information. One particular Div is used to ...

The status value in the result has a whitespace just before the term "success"

Apologies for the unclear question, but I encountered a strange bug in my code. I am trying to show an alert to users informing them that the updates have been successfully completed. Below is the code snippet containing an if() block where the alert shoul ...

Is there a way to manipulate a DOM element using a component?

import { FlagIcon, ChartIcon, ShareIcon, ConnectIcon, HearIcon, AnalyticsIcon, AddIcon, RemoveIcon, } from "../../icons/Icons"; import "./Sidebar.scss"; import ReactDOM from "react-dom"; const Sidebar = () =&g ...

Discovering the data types for node.js imports

When starting a node.js project with express, the code typically begins like this - import express = require('express') const app = express() If I want to pass the variable 'app' as a parameter in typescript, what would be the appropri ...

The `finally` function in promises is failing to execute properly

Currently working with Typescript and I've included import 'promise.prototype.finally' at the beginning of my index.js file (in fact, I've added it in multiple places). Whenever I try to use a promise, I encounter the error message say ...