show progress info and download code (styling is very much in progress)

This commit is contained in:
xenofem 2022-04-27 12:59:14 -04:00
parent f10ee6aa2a
commit 05f33af7e1
2 changed files with 15 additions and 2 deletions

View file

@ -17,6 +17,8 @@
<h2>Files selected:</h2> <h2>Files selected:</h2>
<ul id="file_list"> <ul id="file_list">
</ul> </ul>
<div id="download_link"></div>
<div id="progress"></div>
<script src="upload.js"></script> <script src="upload.js"></script>
</body> </body>
</html> </html>

View file

@ -3,6 +3,8 @@ let files = [];
let socket = null; let socket = null;
let fileIndex = 0; let fileIndex = 0;
let byteIndex = 0; let byteIndex = 0;
let bytesSent = 0;
let totalBytes = 0;
function sendMetadata() { function sendMetadata() {
const metadata = files.map((file) => ({ const metadata = files.map((file) => ({
@ -32,6 +34,8 @@ function sendData() {
const data = currentFile.slice(byteIndex, endpoint); const data = currentFile.slice(byteIndex, endpoint);
socket.send(data); socket.send(data);
byteIndex = endpoint; byteIndex = endpoint;
bytesSent += data.size;
progress.textContent = `${Math.floor(bytesSent * 100 / totalBytes)}%`;
} else { } else {
fileIndex += 1; fileIndex += 1;
byteIndex = 0; byteIndex = 0;
@ -43,6 +47,8 @@ const fileInput = document.getElementById('file_input');
const fileInputMessage = document.getElementById('file_input_message'); const fileInputMessage = document.getElementById('file_input_message');
const fileList = document.getElementById('file_list'); const fileList = document.getElementById('file_list');
const uploadButton = document.getElementById('upload'); const uploadButton = document.getElementById('upload');
const downloadLink = document.getElementById('download_link');
const progress = document.getElementById('progress');
function updateButtons() { function updateButtons() {
if (files.length === 0) { if (files.length === 0) {
@ -95,10 +101,15 @@ uploadButton.addEventListener('click', (e) => {
button.disabled = true; button.disabled = true;
} }
socket = new WebSocket('ws://localhost:3000/upload'); totalBytes = files.reduce((acc, file) => acc + file.size, 0);
socket = new WebSocket(`ws://${window.location.host}/upload`);
socket.addEventListener('open', sendMetadata); socket.addEventListener('open', sendMetadata);
socket.addEventListener('message', (msg) => { socket.addEventListener('message', (msg) => {
if (msg.data === 'ack') { if (bytesSent === 0 && msg.data.match(/^[A-Za-z0-9]+$/)) {
downloadLink.textContent = msg.data;
sendData();
} else if (msg.data === 'ack') {
sendData(); sendData();
} }
}); });