App Router: File Upload File objects are not supported
#50358
-
When attempting to to send a file from a
export default function Home() {
const [pending, startTransition] = useTransition();
const [file, setFile] = useState<File | null>(null);
const handleSubmit = () => {
startTransition(() => uploadImage(file));
};
return (
<main className="flex p-24">
<Input type="file" onChange={e => setFile(e.target?.files[0])} />
<Button onClick={handleSubmit}>Upload</Button>
</main>
);
} What is the recommended way to send a file to a server actions if its unable to serialize a file instead of utilizing a route. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
What I tried firstWith this "use client";
import { uploadFile } from "./actions";
export default function Home() {
return (
<form className="flex flex-col items-end">
<input name="fileUpload" type="file" />
<button
className="text-white bg-blue-700 p-2 rounded"
formAction={uploadFile}
>
Upload!
</button>
</form>
);
} And this action: "use server";
export async function uploadFile(data: FormData) {
const file = data.get("fileUpload");
console.log(file);
} I get this: Screen.Recording.2023-05-26.at.07.36.55.movA fix for your situationSo that means that in your case the problem is that you are not passing a FormData object into your In the fetch API when you pass FormData object, binary transwer is allowed through the multipart/form-data content-type. Do this modification: "use client";
import { useState, useTransition } from "react";
import { uploadFile } from "./actions";
export default function Home() {
const [pending, startTransition] = useTransition();
const [file, setFile] = useState<File>();
const handleSubmit = () => {
if (!file) return;
const form = new FormData();
form.append("fileUpload", file);
startTransition(() => uploadFile(form));
};
return (
<main className="flex p-24">
<input
type="file"
onChange={(e) => setFile(e.target?.files?.[0])}
/>
<button onClick={handleSubmit}>Upload</button>
</main>
);
} I'd recommend using a form as well. Lastly, you need to adapt your |
Beta Was this translation helpful? Give feedback.
-
how can i get the file path because the formData.get("file") only provieds file size and type only i want to upload the image to telegram |
Beta Was this translation helpful? Give feedback.
-
The approach provided by @icyJoseph works - thanks for that! 👍 But it causes a lot of headache in my project due to adjustments regarding types and validation. It would be awesome if there were another way. |
Beta Was this translation helpful? Give feedback.
What I tried first
With this
use client
page component:And this action:
I get this:
Screen.Recording.2023-05-26.at.07.36.55.mov
A fix for your situation
So that means that in your case the problem is that yo…