Add async uploads with progress

This commit is contained in:
Shadowfacts 2021-04-10 16:00:58 -04:00
parent 757c2b696a
commit de7f7eef6a
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
3 changed files with 51 additions and 1 deletions

View File

@ -13,3 +13,5 @@ import "../css/app.scss"
// import socket from "./socket"
//
import "phoenix_html"
import "./async_uploads"

View File

@ -0,0 +1,47 @@
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);
});
});

View File

@ -28,9 +28,10 @@
<% end %>
</table>
<%= form_tag Routes.page_path(@conn, :create_upload, @page.id), method: :post, multipart: true do %>
<%= form_tag Routes.page_path(@conn, :create_upload, @page.id), method: :post, multipart: true, class: "edit-upload-form" do %>
<input type="file" name="file">
<%= submit "Upload" %>
<progress value="0" max="1" style="visibility: hidden;"></progress>
<% end %>
<span><%= link "Back", to: Routes.page_path(@conn, :show, @page.id) %></span>