Select file to upload:
function handleFileUpload() {
const input = document.getElementById('file_to_upload');
const reader = new FileReader();
reader.onloadend = function (e) {
if (this.status === 0 && e.target.files[0]) {
upload(reader, e.target.files[0]);
}
}
input.addEventListener('change', handleFileUpload);
}
function upload(reader, file) {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
xhr.setRequestHeader('Content-Type', file.type);
xhr.onload = function () {
if (xhr.status === 200) {
alert(xhr.responseText);
} else {
console.log(xhr.status, xhr.statusText);
}
};
reader.readAsBinaryString(file);
}