Next.js Discord

Discord Forum

How to get file from form data in edge route

Unanswered
Iridescent shark posted this in #help-forum
Open in Discord
Avatar
Iridescent sharkOP
Does anybody know how to get file from form data in api routes? I tried to use
export const config = {
api: {
bodyParser: false,
},
};

with const formData = await req.formData(); and in development mode it works fine, but if I try to build app it says that config is deprecated?

22 Replies

Avatar
Ray
if you are using app router, you can just remove the config
Avatar
Iridescent sharkOP
if I remove config then I get Request.formData: Could not parse content as FormData. error
Avatar
Ray
are you using page router or app router?
Avatar
Iridescent sharkOP
i have route in /app/api/files/upload
Avatar
Ray
are you sending formData on your client?
Avatar
Iridescent sharkOP
I will send it on client, but right now I'm testing it with postman
Avatar
Ray
ok are you sending form data with postman?
Avatar
Iridescent sharkOP
Image
Avatar
Ray
try x-www-form-urlencoded
Avatar
Iridescent sharkOP
there is no option to send file, only text
Avatar
Ray
but it works right?
Avatar
Iridescent sharkOP
yes, if I send text, I don't get this error
this is code for route
import { Ok, withErrorHandler } from "@/lib/api";
import { BadRequestError } from "@/lib/errors";
import googleStorageService from "@/lib/services/googleStorageService";
import { NextRequest } from "next/server";

export const POST = withErrorHandler(async (req: NextRequest) => {
  const formData = await req.formData(); <--- here I get error

  const file = formData.get("file") as File | null;
  if (!file) {
    throw new BadRequestError("No file provided");
  }

  if (file.size > 1024 * 1024 * 5) {
    throw new BadRequestError("File is too large");
  }

  const buffer = await file.arrayBuffer();
  const fileName = file.name;

  const url = await googleStorageService.upload(fileName, buffer, "tmp");

  const uploadedFile = {
    name: file.name,
    size: file.size,
    type: file.type,
    url,
  };

  return Ok(uploadedFile);
});
Avatar
Ray
I'm confused😵
if you send text and it works?
Avatar
Iridescent sharkOP
yes
I mean it even works if I send form-data but without a file, just a text. I think there is problem with file parsing in req.FormData()
Avatar
Ray
without the bodyParse config?
I would suggest you try submitting with the form in client
no extra configuration needed for parsing the formData in router handler
Avatar
Iridescent sharkOP
ok ill try add write here if it works
Avatar
Ray
ok