#How to get file from form data in edge route

23 messages · Page 1 of 1 (latest)

pearl hill
#

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?

ripe lynxBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

proud gazelle
pearl hill
proud gazelle
#

are you using page router or app router?

pearl hill
#

i have route in /app/api/files/upload

proud gazelle
#

are you sending formData on your client?

pearl hill
#

I will send it on client, but right now I'm testing it with postman

proud gazelle
#

ok are you sending form data with postman?

pearl hill
proud gazelle
#

try x-www-form-urlencoded

pearl hill
#

there is no option to send file, only text

proud gazelle
#

but it works right?

pearl hill
#

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);
});

proud gazelle
#

I'm confused😵

#

if you send text and it works?

pearl hill
#

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()

proud gazelle
#

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

pearl hill
#

ok ill try add write here if it works