TanStackT
TanStack10mo ago
3 replies
wispy-olive

Passing formdata with file to server function but file disappears

Hi there

I have a image uploader in my app that uses a hook to pass the data to a server function but when I try to pass the the formdata to the serverfunction, my function's validator tells me that the file is missing "Missing or invalid file". I am not sure what I am doing wrong:
// snippet
const formData = new FormData();
            formData.append("file", file);
            formData.append("directory", directory);
            for (const [key, value] of formData.entries()) {
                console.log(key, value);
            }
            // Upload using server function
            const result = await uploadFile({ data: formData });


server function:
export const uploadFile = createServerFn({ method: "POST" })
    .validator((formData: FormData) => {
        if (!(formData instanceof FormData)) {
            throw new Error("Invalid form data");
        }

        const file = formData.get("file") as File;
        const directory = (formData.get("directory") as string) || "uploads";

        if (!file) {
            throw new Error("Missing or invalid file"); // this gets triggered!
        }

        return { file, directory };
    })
    .handler(async ({ data }) => {
        try {
            const { file, directory } = data;

            const uploadResponse = await client.uploads.index.post({
                file,
                directory,
            });


Any thoughts? I posted a screenshot of my browser logs showing that the file is there
CleanShot_2025-03-28_at_19.30.592x.png
Was this page helpful?