-
Notifications
You must be signed in to change notification settings - Fork 0
/
UploadGif.svelte
132 lines (111 loc) · 2.45 KB
/
UploadGif.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<script>
import { toast } from "@zerodevx/svelte-toast";
import { fade } from "svelte/transition";
import { push } from "svelte-spa-router";
import axios from "axios";
import LoadingAnimation from "../components/LoadingAnimation.svelte";
import Heading from "../components/Heading.svelte";
let selectedFiles = [];
let gif;
let caption = "";
let loading;
function onFileSelected(e) {
let image = e.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(image);
reader.onload = (e) => {
gif = e.target.result;
};
}
async function submit() {
if (selectedFiles.length === 0) {
return toast.push("Please select a GIF", { classes: ["info"] });
}
const fileSize = selectedFiles[0].size / 1000000;
if (fileSize > 20) {
return toast.push(
"Selected GIF exceeds 20 MB size limit. Please select a different GIF",
{ classes: ["info"] }
);
}
if (caption.length === 0) {
return toast.push("Please enter some text for the caption", { classes: ["info"] });
}
loading = true;
var formData = new FormData();
formData.append("file", selectedFiles[0]);
try {
let res = await axios.post("API_URL/upload", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});
const filename = res.data.filename;
res = await axios.post(
"API_URL/caption",
{
filename,
text: caption,
},
{ filename, text: caption },
{
headers: {
"Content-Type": "application/json",
},
}
);
loading = false;
push(`/result/${res.data.filename}`);
} catch (error) {
loading = false;
toast.push("Server error", { classes: ["warn"] });
}
}
</script>
<main>
<Heading />
<form on:submit|preventDefault={() => {}}>
<input
type="file"
bind:files={selectedFiles}
accept=".gif"
on:change={(e) => onFileSelected(e)}
/>
{#if gif}
<div class="gif" in:fade>
<img src={gif} alt="Selected GIF" />
</div>
{/if}
<p>Enter caption:</p>
<input bind:value={caption} />
<br />
<button on:click={submit} disabled={caption.length === 0 || selectedFiles.length === 0}
>Submit
</button>
</form>
{#if loading}
<LoadingAnimation />
{/if}
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin-left: auto;
margin: 0 auto 5% auto;
}
img {
height: 10%;
}
h1 {
color: white;
font-size: 5em;
font-weight: 100;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>