-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDropImage.svelte
82 lines (71 loc) · 2.49 KB
/
DropImage.svelte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<svelte:options customElement="drop-image" />
<script>
import { onMount } from "svelte";
import "bootstrap/dist/css/bootstrap.min.css";
// Drag and Drop an image
// Reference: https://transloadit.com/devtips/implementing-file-uploads-with-bootstrap-5/
const ALLOWED_IMAGE_TYPES = ["image/jpeg", "image/png"];
const MAX_SIZE = 5 * 1024 * 1024; // 5MB
const DEFAULT_IMAGE = "/drag_and_drop.png";
var {
maxSize = MAX_SIZE,
defaultImage = DEFAULT_IMAGE,
callback,
} = $props();
var DropZone;
var FileInput;
var ErrorMessage;
var Img;
const toBase64 = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
});
onMount(() => {
Img.ondragover = (e) => {
e.preventDefault();
Img.classList.add("bg-light");
Img.classList.add("border-primary");
};
Img.ondragleave = (e) => {
Img.classList.remove("bg-light");
Img.classList.remove("border-primary");
};
Img.ondrop = async (e) => {
e.preventDefault();
Img.classList.remove("bg-light");
Img.classList.remove("border-primary");
ErrorMessage.classList.add("d-none");
try {
const file = e.dataTransfer.files[0];
if (!ALLOWED_IMAGE_TYPES.includes(file.type)) {
throw new Error(
"Invalid file type. Please upload JPEG or PNG.",
);
}
if (file.size > maxSize) {
throw new Error("File too large. Maximum size is 5MB.");
}
FileInput.files = e.dataTransfer.files;
const b64Image = await toBase64(FileInput.files[0]);
Img.src = b64Image;
callback(b64Image);
} catch (error) {
ErrorMessage.textContent = error.message;
ErrorMessage.classList.remove("d-none");
}
};
});
</script>
<!-- svelte-ignore a11y_missing_attribute -->
<img bind:this={Img} src={defaultImage} class="border border-2 w-100" />
<div bind:this={ErrorMessage} class="alert alert-danger d-none mt-2"></div>
<input
type="file"
class="d-none"
accept="image/jpeg,image/png"
bind:this={FileInput}
/>
<slot />