Error posting image using formdata: "NotSupportedError: multipart/form-data not supported"

1.3k views Asked by At

I am using Next.js version 13.4.1 and trying to post a file to the server using multipart/form-data. However, when attempting to do so, I receive an error message stating that the format is not supported. I have seen a few blogs and other developers successfully using this method, so I believe it may be a bug within my code or within Next.js itself.

I am working within the app directory of my project and I am attempting to post an image file to the server. Within my frontend code, I have implemented the necessary functions to handle the image upload. The handleDragOver, handleDragLeave, and handleDrop functions allow for the user to drag and drop an image onto the designated area. The create function then handles the form submission, creating a new instance of FormData and setting the appropriate values.

Frontend

const handleDragOver = (event: any) => {
    event.preventDefault();
    setDragOver(true);
};

const handleDragLeave = (event: any) => {
    event.preventDefault();
    setDragOver(false);
};

const handleDrop = (event: any) => {
    event.preventDefault();
    setDragOver(false);
    const file = event.dataTransfer.files[0];
    setImage(file);
};

const create = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (!image) {
        return;
    }

    const formData = new FormData();

    formData.set("name", name);
    formData.set("url", url);
    formData.set("image", image, image.name);

    const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/category`, {
        method: "POST",
        body: formData,
    });
    const data = await response;
    console.log(data);
};

Backend

On the backend, I have implemented a POST function to handle the request. Within this function, I am attempting to retrieve the form data using the request.formData() method.

import prisma from "@/libs/prisma";
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
  const formData = await request.formData();
  console.log(formData);
}

However, when I submit the form, I receive an error message stating that the multipart/form-data format is not supported. I have checked my code against other examples online and do not see any obvious issues. I suspect that this may be a bug within Next.js or a compatibility issue with my particular setup.

I have tried several solutions to resolve the issue I am facing with posting my file to the server using multipart/form-data. Firstly, I tried using a library that was suggested on some blog posts, but it did not work. Then, I tried updating all the dependencies including the Next.js version, but the issue persisted. I even tried to find a solution on the official Discord server for Next.js and on the internet, but I was not able to find any satisfactory answer.

I was expecting to find a solution that would allow me to post my file to the server successfully using multipart/form-data. However, despite trying several solutions, I have not been able to resolve the issue yet. I am still actively searching for a solution and will continue to explore different options until I am able to successfully post the file to the server.

The error:

- error NotSupportedError: multipart/form-data not supported
    at NextRequest.formData (node:internal/deps/undici/undici:2383:19)
    at POST (webpack-internal:///(sc_server)/./src/app/api/category/route.ts:31:36)
    at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:244:43)
    at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/lib/trace/tracer.js:109:36)     
    at NoopContextManager.with (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:360:30)
    at ContextAPI.with (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:30:58)
    at NoopTracer.startActiveSpan (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:953:34)
    at ProxyTracer.startActiveSpan (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:993:36)
    at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/lib/trace/tracer.js:98:107)     
    at NoopContextManager.with (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:360:30)
    at ContextAPI.with (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:30:58)
    at NextTracerImpl.trace (webpack-internal:///(sc_server)/./node_modules/next/dist/server/lib/trace/tracer.js:98:32)
    at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:232:53)
    at AsyncLocalStorage.run (node:async_hooks:330:14)
    at Object.wrap (webpack-internal:///(sc_server)/./node_modules/next/dist/server/async-storage/static-generation-async-storage-wrapper.js:39:24)
    at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:186:97)
    at AsyncLocalStorage.run (node:async_hooks:330:14)
    at Object.wrap (webpack-internal:///(sc_server)/./node_modules/next/dist/server/async-storage/request-async-storage-wrapper.js:77:24)
    at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:185:75)
    at AsyncLocalStorage.run (node:async_hooks:330:14)
    at AppRouteRouteModule.execute (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:182:56)
    at AppRouteRouteModule.handle (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:333:41)
    at RouteHandlerManager.handle (C:\Users\xxx\OneDrive\Plocha\skaut-frystak\node_modules\next\dist\server\future\route-handler-managers\route-handler-manager.js:28:29)
    at doRender (C:\Users\xxx\OneDrive\Plocha\skaut-frystak\node_modules\next\dist\server\base-server.js:935:58)
    at cacheEntry.responseCache.get.incrementalCache.incrementalCache (C:\Users\xxx\OneDrive\Plocha\skaut-frystak\node_modules\next\dist\server\base-server.js:1161:34)
    at C:\Users\xxx\OneDrive\Plocha\skaut-frystak\node_modules\next\dist\server\response-cache\index.js:99:42
    at ResponseCache.get (C:\Users\xxx\OneDrive\Plocha\skaut-frystak\node_modules\next\dist\server\response-cache\index.js:149:11)
    at DevServer.renderToResponseWithComponentsImpl (C:\Users\xxx\OneDrive\Plocha\skaut-frystak\node_modules\next\dist\server\base-server.js:1080:53)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'UND_ERR_NOT_SUPPORTED'
}
2

There are 2 answers

1
Tom On BEST ANSWER

After some research, I found that the problem was with the version of NodeJS I was using. I was running version 18.10, but when I upgraded to version 20.1.0 (which is the current version at the time of writing), the formData started to work.

So it seems that the issue was related to the NodeJS version. I would recommend trying to upgrade to the latest version and see if that solves the problem for people in the future. You can download it from the official NodeJS website.

0
Rolf Chen On

That was really helpful and saved my day also! Unfortunately I can't upgrade to node 20 just yet. Going to have to fallback to using pages/api/. Seems like you can use both structures at the same, and NextJS will manage the routing correctly still.