Handle file uploads in SvelteKit, the sane way -
3 min read
Written by Odyssey346
606 words
Handle file uploads in SvelteKit, the sane way #
I was working on a project which required file uploads. I was not sure how to do it, because there wasn’t a whole lot of documentation. I found an article, but it did not use form file (which is what I wanted), so I figured out how to do it myself.
Let’s get started #
First, we need to create a form in your page. It should look something like this:
|
|
The form requires multipart/form-data or else SvelteKit won’t be able to handle it.
Now, create a file called +page.server.ts
(or .js, depending on what you chose for your project. I assume you are using TypeScript) in the same folder as your page. It should look something like this:
|
|
Now in your +page.svelte
, we can use the data returned from the form action. You need to import import type { PageData, ActionData } from "./$types";
, and then create a variable like this: export let form: ActionData;
. This allows you to use the data returned from the form action. Here’s a complete example of what your +page.svelte
should look like:
|
|
Pretty simple, right? Now file uploads should work in your SvelteKit app!
📧 Reply to this post via E-mail