How to get file from form data in edge route
Unanswered
Iridescent shark posted this in #help-forum
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?
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
if you are using app router, you can just remove the config
Iridescent sharkOP
if I remove config then I get
Request.formData: Could not parse content as FormData.
errorare you using page router or app router?
Iridescent sharkOP
i have route in /app/api/files/upload
are you sending formData on your client?
Iridescent sharkOP
I will send it on client, but right now I'm testing it with postman
ok are you sending form data with postman?
Iridescent sharkOP
try x-www-form-urlencoded
Iridescent sharkOP
there is no option to send file, only text
but it works right?
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);
});
I'm confused😵
if you send text and it works?
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()
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
Iridescent sharkOP
ok ill try add write here if it works
ok