ciscoheat / sveltekit-superforms

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

Custom fetch/XMLHttpRequest when submitting (was: how to implement progress bar for file uploading) #434

Closed IslamZaoui closed 1 month ago

IslamZaoui commented 3 months ago

Hello, can we implement a progress bar with superforms? I didn't find anything on the web.

c0repwn3r commented 1 month ago

I need this too - any solutions?

IslamZaoui commented 1 month ago

I need this too - any solutions?

You can use xmlhttprequest to do this and use progress event

c0repwn3r commented 1 month ago

How do we do this in the context of Superforms? I've scoured over the docs, and there doesn't seem to be any way to intercept the submit handler while still utilizing use:enhance. SvelteKit itself always calls fetch and there doesn't appear to be any way of stopping it.

ciscoheat commented 1 month ago

That's right, as Superforms is utilizing the SvelteKit fetch, it's not possible to do it easily. What you can do is to call cancel in onSubmit, then create the xmlhttprequest yourself and handle the progress.

It's not a bad feature really, so maybe it can be added to the library. There are already two "modifier functions" for the onSubmit event, jsonData and validators. A customRequest function could be added that will replace the default fetch.

ciscoheat commented 1 month ago

Added now with v2.16.0: https://superforms.rocks/concepts/events#customrequest

c0repwn3r commented 1 month ago

Damn! That was fast. Thanks!

groupunknown commented 1 month ago

It works great if it's just one file, but it would be interesting to listen to events coming from the server.

My +page.server.ts sends multiple files to cloudflare's R2, and I have some functions that return the upload progress of each file and the id.

I'm new to Svelte, haven't yet figured out a method to send this information to +page.svelte and update the items on the page.

Is there any way to do this without using websocket?

+page.server.ts
...
const organizedFiles = await organizeFiles(files, (index, percentage) => {
       console.log(`File ${index + 1}: ${percentage}% uploaded`);
});