Next.js Discord

Discord Forum

Get a file from a FormData

Answered
Sphecid wasp posted this in #help-forum
Open in Discord
Avatar
Sphecid waspOP
Hey !
I have a formdata, and I get this formdata when submitting the form.
In this form, user can attach a file and I want to get this file and upload it in my server. But how do I get the file ?
Answered by Alfonsus Ardani
If you pass the formData through a server action you can easily get them using the form data API

// front-end
<form action={serverAction}>
  <input type="file" name="myfile1"/>
</form>

// back-end
async function serverAction(formData: FormData){
  const file = formData.get('myfile1') as File
}


[Here is the demo](https://x.com/alfonsusac/status/1867420899026382949)
View full answer

10 Replies

Avatar
Sphecid waspOP
btw, I'm doing this in an action file. Maybe I should create an API and then send the file via this ?
Avatar
If you pass the formData through a server action you can easily get them using the form data API

// front-end
<form action={serverAction}>
  <input type="file" name="myfile1"/>
</form>

// back-end
async function serverAction(formData: FormData){
  const file = formData.get('myfile1') as File
}


[Here is the demo](https://x.com/alfonsusac/status/1867420899026382949)
Answer
Avatar
Sphecid waspOP
Since I don't use typescript, I can just use formdata.get("") ?
Avatar
yep
Avatar
Sphecid waspOP
thanks !!
Avatar
just make sure the name is the same
but if you are ever confused, you can always console.log(formData) and see what it does xD
Avatar
Sphecid waspOP
yea I saw it has information but I wasn't sure if it was the file are just infos
well I'm stupid it literraly said File
Avatar
it can happen to anyone. we are all stupid at times