Utilizing Next.js with formidable for efficient parsing of multipart/form-data

I've been working on developing a next.js application that is supposed to handle multipart/form-data and then process it to extract the name, address, and file data from an endpoint.

Although I attempted to use Formidable library for parsing the formdata object, I'm encountering difficulties in making it function properly. The fields and file values are all showing up as empty objects {}. Are there any recommendations or tips on how to effectively parse the form data?

export default function supplier(req, res) {
  if (req.method == 'POST') {
    //console.log("req: \n",req);
    console.log("req body: \n",req.body);
    //console.log("req.file: \n",req.headers);
    //console.log("req.address: \n",req.body.address);
    
    const form = new formidable.IncomingForm();
    //console.log("form: \n",form);
    //const form = new multiparty.Form();
    let FormResp = new Promise((resolve,reject)=>{
      form.parse(req, (err, fields, files)=>{
          console.log("fields: ",fields);
          console.log("files: ",files);
          //await saveFile(files.file);
          //await saveDB();
          return res.status(201).send("");
      });
    });
  } else {
    // Handle any other HTTP method
    return res.status(405).json({ error: `Method '${req.method}' Not Allowed` });
  }

const handleSubmit = async (event) => {
    event.preventDefault();

    const formdata = new FormData();
    const json = JSON.stringify({"name":event.target.name.value, "address":event.target.address.value, "file": createObjectURL})
    
    formdata.append("file", image);
    formdata.append("name", event.target.name.value);
    formdata.append("address", event.target.address.value);
    console.log("formdata: \n", formdata);

    //var request = new XMLHttpRequest();
    //request.open("POST", "/api/supplier");
    //request.send(formData:body);

    const response = await fetch("/api/supplier",{method: 'POST', body: formdata, "content-type":"multipart/form-data"});

    //const result = await response.json()
    //console.log(result)
    
};

------WebKitFormBoundaryiu8apU5i3hWyORTY
Content-Disposition: form-data; name="name"

Hello
------WebKitFormBoundaryiu8apU5i3hWyORTY
Content-Disposition: form-data; name="address"

addressssssssss
------WebKitFormBoundaryiu8apU5i3hWyORTY--

req body: 
 ------WebKitFormBoundary92WJpSOKb0mEfOAH
Content-Disposition: form-data; name="file"; filename="attachment.svg"
Content-Type: image/svg+xml

<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 48 48" viewBox="0 0 48 48"><path d="M35.5,34V16c0-0.83-0.67-1.5-1.5-1.5s-1.5,0.67-1.5,1.5v18c0,4.69-3.81,8.5-8.5,8.5s-8.5-3.81-8.5-8.5V11
        c0-3.03,2.47-5.5,5.5-5.5s5.5,2.47,5.5,5.5v21.5c0,1.38-1.12,2.5-2.5,2.5s-2.5-1.12-2.5-2.5V13c0-0.83-0.67-1.5-1.5-1.5
        s-1.5,0.67-1.5,1.5v19.5c0,3.03,2.47,5.5,5.5,5.5s5.5-2.47,5.5-5.5V11c0-4.69-3.81-8.5-8.5-8.5s-8.5,3.81-8.5,8.5v23
        c0,6.34,5.16,11.5,11.5,11.5S35.5,40.34,35.5,34z"/></svg>
------WebKitFormBoundary92WJpSOKb0mEfOAH

Answer №1

Were you referring to multipart/form-data in your original query?

If you're encountering issues using formidable in Next.js, a workaround is to turn off the default body parser. You can achieve this by exporting a configuration object from your API route and setting api.bodyParser to false. This will maintain the request stream as-is so that formidable can correctly parse it.

To implement this workaround, simply include the following lines of code:

export const config = {
  api: {
    bodyParser: false,
  },
}

export default async function yourRoute(
  req: NextApiRequest,
  res: NextApiResponse
) { }

Answer №2

It may seem like it's too late to mention, but avoid trying to directly return res inside a Promise. Instead, resolve the promise first and then send the response based on the output.

export default function supplier(req, res) {
  if (req.method !== 'POST') {
    // Handle any other HTTP method
    res.status(405).json({ error: `Method '${req.method}' Not Allowed` });
    return;
  }
    
  let FormResp = new Promise((resolve,reject) => {
    const form = formidable();
    form.parse(req, (err, fields, files)=>{
      if (err) reject(err);
      else resolve({ fields, files });
    });
  });

  const { fields } = FormResp;
  console.log(fields);
}

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

Unable to dynamically translate special characters using npm latinize

When translating German special characters to English using latinize, the module only works when strings are passed within single or double quotes. However, it does not work when storing them inside a variable. import latinize from 'latinize'; ...

Updating a React JS State using a Parameter

Is it feasible to develop a function that accepts a parameter (either a string of the state name or the actual state) and then assigns the state related to the parameter? SetState(x) { // Suppose x can be any state we have already defined (it sh ...

Display dynamic HTML content using Contentful and Next.js

Currently in the process of creating a website with Next.js and Contentful. I am aiming to display HTML content, such as <span style="font-size: 18px">View</span>, within Contentful rich text fields. Uncertain if this is attainable. ...

Using Javascript function with ASP.NET MVC ActionLink

I need help with loading a partial view in a modal popup when clicking on action links. Links: @model IEnumerable<string> <ul> @foreach (var item in Model) { <li> @Html.ActionLink(item, "MyAction", null, new ...

How can we effectively create reusable modals in React with the most efficient approach?

Currently, I am developing an application using React and Material UI. In order to streamline the use of Modals across multiple pages, I have implemented a global modal context that dynamically populates the modal with different props based on state change ...

Loading data into a Dojo ItemFileReadStore using Grails and the "render as JSON" method

I have developed a controller method that generates a JSON "file" on-the-fly when the corresponding URL is accessed. This file exists in memory and not saved on disk, as it's dynamically created when the URL is hit. I'm attempting to utilize this ...

Should we employ getAttribute() or avoid it entirely? That is the ultimate query

Similar Topic: JavaScript setAttribute vs .attribute= javascript dom, how to handle "special properties" as versus attributes? On multiple occasions, I've encountered criticism in forums or Usenet about the way I access attributes i ...

CriOS unable to recognize OPTIONS request from Tomcat 8

My application uses POST requests with CORS for backend services (from www.mydomain.com to api.mydomain.com). The backend is served by a Tomact8 server, implementing a CORSResponseFilter as shown below: public class CORSResponseFilter implements Container ...

Looking to confirm client-side text in NodeJS?

As I work on constructing a to-do list, one challenge I am encountering is confirming that the correct task has been checked off. While considering using unique IDs for each individual task may seem like a solution, there is still the risk of users manipul ...

Tips for importing and exporting icons in a way that allows for dynamic importing using a string parameter

I am facing an issue with dynamically importing SVG icons in React Native. Initially, I tried using the following code snippet: const icon = require(`@src/assets/icons/${iconName}`) However, after realizing that this approach wouldn't work for me, I ...

The click function for the responsive navbar hamburger is not functioning properly

Having some trouble with the code not working in responsive mode. I've tested it on a 600px screen and the hamburger button doesn't seem to work (I click it and nothing happens). I've gone through both the CSS and JS multiple times but can&a ...

What is the best way to show a message on a webpage after a user inputs a value into a textbox using

I have a JSFiddle with some code. There is a textbox in a table and I want to check if the user inserts 3000, then display a message saying "Yes, you are correct." Here is my jQuery code: $("#text10").keyup(function(){ $("#text10").blur(); ...

jQuery unable to find designated elements in uploaded templates

I have a specific route linked to a specific controller and view: app.config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/create', { templateUrl: 'partials/form/form.html', controlle ...

Type of Multiple TypeScript Variables

Within my React component props, I am receiving data of the same type but with different variables. Is there a way to define all the type variables in just one line? interface IcarouselProps { img1: string img2: string img3: string img4: string ...

The Philosophy Behind Structuring Node.js Modules

There appears to be a common understanding regarding the directory structure in node.js, but I have not come across any official documentation on this topic. Based on my exploration of open source projects, it seems that most projects typically include a ...

Sliding elements horizontally with jQuery from right to left

I recently purchased a WordPress theme and I'm looking to customize the JavaScript behavior when the page loads. Currently, my titles animate from top to bottom but I want to change this behavior dynamically. You can view it in action here: I have ...

Creating a new row with a dropdown list upon clicking a button

I want to include a Textbox and dropdown list in a new row every time I click a button. However, I seem to be having trouble with this process. Can someone assist me in solving this issue? Thank you in advance. HTML <table> <tr> ...

Link JSON in JavaScript using field identifiers

I've been working on incorporating JSON data into my JavaScript code, and the JSON structure I am dealing with is as follows: { "status":"ok", "count":5, "pages":1, "category":{ "id":85, "slug":"front-page-active", "title":"Front ...

Mongoose: An unexpected error has occurred

Recently, I developed an express app with a nested app called users using Typescript. The structure of my app.js file is as follows: ///<reference path='d.ts/DefinitelyTyped/node/node.d.ts' /> ///<reference path='d.ts/DefinitelyTyp ...

Is there a way to customize the Color Palette in Material UI using Typescript?

As a newcomer to react and typescript, I am exploring ways to expand the color palette within a global theme. Within my themeContainer.tsx file, import { ThemeOptions } from '@material-ui/core/styles/createMuiTheme'; declare module '@mate ...