plz / static / js / user.js
38 lines · 30 sloc · 869 bytes · 5d8107cb28727996daed016b0c79a9346f864d2b
Raw
1const MEGABYTE_IN_BYTES = 1024 * 1024;
2
3function selectAvatar() {
4 const fileInputEl = document.createElement("input");
5 fileInputEl.type = "file";
6 fileInputEl.accept = "image/*";
7
8 fileInputEl.onchange = async function (event) {
9 const file = event.target.files[0];
10 const fileSize = file.size;
11
12 if (fileSize > MEGABYTE_IN_BYTES) {
13 alert("This file is too large to be uploaded. Files larger than 1 MB are not currently supported");
14 return;
15 }
16
17 await uploadAvatar(file);
18 }
19
20 fileInputEl.click();
21}
22
23async function uploadAvatar(file) {
24 const formData = new FormData();
25 formData.append("file", file);
26
27 const response = await fetch("/api/v1/users/avatar", {
28 method: "POST",
29 body: formData
30 });
31 const json = await response.json();
32
33 if (json.success) {
34 location.reload();
35 } else {
36 alert(json.message);
37 }
38}
39