ciscoheat / sveltekit-superforms

Making SvelteKit forms a pleasure to use!
https://superforms.rocks
MIT License
2.11k stars 62 forks source link

Returning files from load function does not work #409

Open szethh opened 4 months ago

szethh commented 4 months ago

Description I want to load some default data from a database to initially populate the form. This includes some files.

This seems to work server-side. However, the client does not receive the files. This is inside my load function:

// an example of a file that would come from s3 or whatever
const data = {
  files: [
    new File(['hello'], 'hello.txt', { type: 'text/plain' })
  ]
}

// we validate
const form = await superValidate(data, zod(schema))

console.log('valid on server', form.valid)  // true
console.log('files on server', form.data.files)  // [<the file object we created above>]

return withFiles({ form });

On the client:

$: console.log('files in client', $form.files) // []

If I have more fields in my schema/initial data, those pass through just fine. There are no validation errors anywhere, but the files array never gets to the client.

If applicable, a MRE Use this template project to create a minimal reproducible example that you can link to here: https://sveltelab.dev/github.com/ciscoheat/superforms-examples/tree/zod (right click to open in a new tab)

See the console logs in the repro. The file is validated fine in the server, but the client does not receive it. https://www.sveltelab.dev/zqpke6y03pcgu3s

szethh commented 4 months ago

just saw the implementation of withFiles, turns out it actually just removes the files.

is there another way of sending files as initial values?

my use case is a form that is submitted with some attachments, and then can be edited again. the attachments would be sent from the server to the client such that the attachments can be edited.

i can do this with an api route that i fetch from the client but i was hoping there was an "intended" (superforms-wise) way to do it.

ciscoheat commented 4 months ago

SvelteKit cannot serialize File objects, so you need to handle it yourself, base64-encode the data for example and send it as a string in the load function data, then create the File object on the client before calling superForm.