vercel / next.js

The React Framework
https://nextjs.org
MIT License
122.91k stars 26.28k forks source link

Docs: How to pass an input file (like a PDF a user uploaded through a <input type="file"/> to a NEXTJS API route, and how to read this file in the API route (to then upload it to Google Cloud Storage bucket? #41680

Open damiano216 opened 1 year ago

damiano216 commented 1 year ago

What is the improvement or update you wish to see?

Docs: HI would like to see how to pass an input file (like a PDF a user uploaded through a HTML input field) to a NEXTJS API route, and how to read this file in the API route. Thanks

Is there any context that might help us understand?

Hello,

I have a input file which I upload through a <input type="file" />

I would like to send this file to my API route like this: ` const formData = new FormData(); formData.append("file", file);

  await fetch("/api/upload-file-in-cloud-storage", {
    method: "POST",
    body: JSON.stringify({ formData: formData }),
  });`

And finally I would like to read this file in my API route like this: export default async function handler(req, res) { try { console.log(req.body); //this prints an empty formData {"formData":{}}. How can I acces his content?? } catch (error) { } }

However the req.body seems to have an empty formData. Could you please make an example on how to pass an input file (PDF, Word, PPT, Excel....) to the API route AND how to read this file in the API route?

Does the docs page already exist? Please link to it.

No response

DX-1667

lachlanjc commented 1 year ago

Generally you don’t want to upload the files to your function first—it’ll way lower your bandwidth usage & be more reliable to use an API Route to create a presigned upload URL, send that to the frontend, & have the client upload directly to the storage provider.

Check out this example: https://github.com/leerob/nextjs-gcp-storage

For AWS S3: https://github.com/vercel/examples/tree/main/solutions/aws-s3-image-upload