Next.js Discord

Discord Forum

upload images with multiparty, 500 error

Answered
Waterman posted this in #help-forum
Open in Discord
Hello, using next js 13, following old tutorial and running into some issues:

In the video he uses multiparty and i don't know if my code looks correct,
My problem might not even be related to the package I am using but I would appreciate all help.

I also get an error which looks like this:
error unhandledRejection: Error [TypeError]: req.on is not a function

full error in picture.
also the error in the browser is displayed in a picture too

code: (route.ts)
import { NextRequest, NextResponse } from "next/server";
import multiparty from "multiparty";

export const POST = async (req: NextRequest) => {
  const form = new multiparty.Form();
  const { fields, files } = new Promise((resolve, reject) => {
    form.parse(req, (err, fields, files) => {
      if (err) {
        reject(err);
      } else {
        resolve({ fields, files });
      }
    });
  });
  console.log(files.length);
  return NextResponse.json("OK");
};



export const config = {
  api: { bodyParser: false },
};
 
Answered by joulev
Are you sure you sent a formData along with the request?
View full answer

9 Replies

oh ok thanks, I now tried this code:
import { NextRequest, NextResponse } from "next/server";

export const POST = async (req: NextRequest) => {
  const formData = await req.formData();
  const file = formData.get("image");

  console.log(file);



  return NextResponse.json("OK");
};
but it just logged null in the console?
Answer
I do this when sending, I tried console log above "const res" and I did get the data correctly
async function uploadImage(ev) {
    const files = ev.target?.files;
    if (files?.length > 0) {
      const data = new FormData();
      for (const file of files) {
        data.append("file", file);
      }
      const res = await fetch("/api/upload", {
        method: "POST",
        body: data,
      });
    }
  }
@joulev Are you sure you sent a formData along with the request?
I don't really know the issue
the problem was that I had to change to "file" when getting the getting the info from formData, thanks for the help:)