Get a file from a FormData
Answered
Sphecid wasp posted this in #help-forum
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 ?
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
[Here is the demo](https://x.com/alfonsusac/status/1867420899026382949)
// 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)
10 Replies
Sphecid waspOP
btw, I'm doing this in an action file. Maybe I should create an API and then send the file via this ?
If you pass the formData through a server action you can easily get them using the form data API
[Here is the demo](https://x.com/alfonsusac/status/1867420899026382949)
// 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
Sphecid waspOP
Since I don't use typescript, I can just use formdata.get("") ?
Sphecid waspOP
thanks !!
just make sure the
name
is the samebut if you are ever confused, you can always console.log(formData) and see what it does xD
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
it can happen to anyone. we are all stupid at times