Created
September 29, 2023 17:27
-
-
Save aarongilly/494dc7526c44032f764c7f74a286aa16 to your computer and use it in GitHub Desktop.
Svelte File Input Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts"> | |
/** | |
* When a file is dropped here (or selected via browsing) this is the function that will be called back | |
*/ | |
export let fileCallback: (file: File)=>any | |
function handleDrop(ev: any) { | |
// Prevent default behavior (Prevent file from being opened) | |
ev.preventDefault(); | |
(<HTMLDivElement>ev.target).classList.remove("drug"); | |
if (ev.dataTransfer.items) { | |
// Use DataTransferItemList interface to access the file(s) | |
[...ev.dataTransfer.items].forEach((item, i) => { | |
// If dropped items aren't files, reject them | |
if (item.kind === "file") { | |
const file = item.getAsFile(); | |
processFile(file); | |
} | |
}); | |
} else { | |
// Use DataTransfer interface to access the file(s) | |
[...ev.dataTransfer.files].forEach((file, i) => { | |
processFile(file.name); | |
}); | |
} | |
} | |
function handleDragOver(e: DragEvent) { | |
e.preventDefault(); | |
(<HTMLDivElement>e.target).classList.add("drug"); | |
} | |
function handleClick(e: Event) { | |
let input = document.querySelector("#hidden-input") as HTMLInputElement; | |
input.click(); | |
} | |
function handleInput(e: any) { | |
const files = (<HTMLInputElement>e.target).files!; | |
const file = files.item(0)!; | |
processFile(file); | |
} | |
function processFile(file: File) { | |
//console.log(file) | |
fileCallback(file); | |
} | |
</script> | |
<div | |
class="text-center items-center py-6 border-1 hover:cursor-pointer hover:text-xl border-gray-500 border hover:ring-4 hover:text-black hover:bg-blue-300 hover:border-blue-500 duration-300" | |
on:click={handleClick} | |
on:keypress={handleClick} | |
on:drop={handleDrop} | |
on:dragover={handleDragOver} | |
> | |
<span>Drop a file here</span> | |
<input | |
id="hidden-input" | |
type="file" | |
accept=".json" | |
class="invisible absolute h-0 w-0" | |
on:input={handleInput} | |
/> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment