How to Handle File Upload in Svelte: Simple Guide
<input type="file"> element and listening to its change event to access the selected files via event.target.files. Then, you can process or send these files to a server using JavaScript's FormData API.Why This Happens
Developers often try to bind the file input value directly to a variable using Svelte's bind:value, but this does not work because file inputs are read-only for security reasons. This causes the file data to be unavailable or empty when trying to upload.
<script> let file; </script> <input type="file"> <p>Selected file: {file ? file.name : 'None'}</p>
The Fix
Instead of binding the file input's value, listen to the change event on the input. Access the selected files from event.target.files and store them in a variable. This way, you can handle single or multiple file uploads properly.
<script> let files = []; function handleFileChange(event) { files = Array.from(event.target.files); } async function uploadFiles() { const formData = new FormData(); files.forEach(file => formData.append('files', file)); // Example: send to server // await fetch('/upload', { method: 'POST', body: formData }); } </script> <input type="file" multiple on:change={handleFileChange} aria-label="Upload files"> {#if files.length > 0} <ul> {#each files as file} <li>{file.name} ({Math.round(file.size / 1024)} KB)</li> {/each} </ul> <button on:click={uploadFiles}>Upload</button> {/if}
Prevention
Always use the change event to get files from file inputs instead of trying to bind their value. Use FormData to send files to servers. Add aria-label for accessibility and support multiple files with the multiple attribute if needed.
Related Errors
Common mistakes include trying to bind value on file inputs, forgetting to convert FileList to an array, or not using FormData when uploading files. These cause empty uploads or runtime errors.