How to Image Upload With Preview in Svelte

How to Image Upload With Preview in Svelte

05/22 By frontendshape

In this tutorial we will see how to upload image with preview in sveltejs. For this styling we will use Tailwind CSS. First you need to install & setup svelte with tailwind css or you can use <svelte:head> special elements to import tailwind css cdn.

How to Install Tailwind CSS 3 in Svelte


Image Upload Preview in Svelte

<svelte:head>
    <script src="https://cdn.tailwindcss.com"></script>
</svelte:head>

<script>
    let input;
    let container;
    let image;
    let placeholder;
    let showImage = false;

    function onChange() {
        const file = input.files[0];

        if (file) {
            showImage = true;

            const reader = new FileReader();
            reader.addEventListener("load", function () {
                image.setAttribute("src", reader.result);
            });
            reader.readAsDataURL(file);

            return;
        }
        showImage = false;
    }
</script>
<div>
    <h1 class="text-2xl font-bold">Image Preview on File Upload</h1>
    <input bind:this={input} on:change={onChange} type="file"
        class="w-full px-3 py-2 border border-gray-300 rounded-md file:py-2 file:px-4 file:rounded-full file:border-0" />
    <div bind:this={container} class="flex items-center justify-center h-40 max-w-sm mt-4 border">
        {#if showImage}
        <img bind:this={image} src="" alt="Preview" />
        {:else}
        <span bind:this={placeholder} class="text-blue-600">Image Preview</span>
        {/if}
    </div>
</div>
image upload sveltekit

image upload sveltekit






Enter Your Search Query