48 lines
1.4 KiB
JavaScript
48 lines
1.4 KiB
JavaScript
|
document.addEventListener("DOMContentLoaded", () => {
|
||
|
const form = document.querySelector(".edit-upload-form");
|
||
|
if (!form) return;
|
||
|
|
||
|
const button = form.querySelector("button[type=submit]");
|
||
|
button.addEventListener("click", (event) => {
|
||
|
event.preventDefault();
|
||
|
button.setAttribute("disabled", "true");
|
||
|
|
||
|
const file = form.querySelector("input[type=file]").files[0];
|
||
|
if (!file) return;
|
||
|
|
||
|
const pageID = /^\/pages\/(\d+)\/edit$/.exec(window.location.pathname)[1];
|
||
|
const progress = form.querySelector("progress");
|
||
|
progress.style.visibility = "visible";
|
||
|
|
||
|
const fd = new FormData();
|
||
|
fd.append("_csrf_token", form.querySelector("input[type=hidden]").value);
|
||
|
fd.append("file", file);
|
||
|
|
||
|
// it's 2021 and fetch doesn't have progress support, smh
|
||
|
const xhr = new XMLHttpRequest();
|
||
|
xhr.upload.addEventListener("progress", (event) => {
|
||
|
const newVal = event.loaded / event.total;
|
||
|
if (newVal >= 1) {
|
||
|
progress.removeAttribute("value");
|
||
|
} else {
|
||
|
progress.value = newVal;
|
||
|
}
|
||
|
});
|
||
|
xhr.addEventListener("load", () => {
|
||
|
window.location.reload();
|
||
|
});
|
||
|
xhr.addEventListener("error", (event) => {
|
||
|
console.error(event);
|
||
|
progress.style.visibility = "hidden";
|
||
|
alert("Upload error");
|
||
|
});
|
||
|
xhr.addEventListener("abort", (event) => {
|
||
|
console.error(event);
|
||
|
progress.style.visibility = "hidden";
|
||
|
alert("Upload aborted");
|
||
|
});
|
||
|
xhr.open("POST", `/pages/${pageID}/uploads`);
|
||
|
xhr.send(fd);
|
||
|
});
|
||
|
});
|