Below is my code to preview a file. the if statement always returns false. so the code inside never gets run. when I log out a file it returns type: image/png but it does not accept this when comparing in the if statement
let fileInput = document.getElementById('files')
let filesContainer = document.getElementById('files-container')
let numberOfFiles = document.getElementById('number-of-files')
function preview() {
filesContainer.innerHTML = ''
numberOfFiles.textContent = `${fileInput.files.length} Files Selected`
for (i of fileInput.files) {
let reader = new FileReader()
let figure = document.createElement('figure')
let figCap = document.createElement('figcaption')
figCap.innerText = i.name
console.log(i)
figure.appendChild(figCap)
reader.onload = () => {
if (i.type.match('image/png')) {
consel.log('PNG')
let img = document.createElement('img')
img.src = reader.result
figure.appendChild(img)
}
/*
if (i.type == "image/jpeg" || i.type == "image/png" || i.type == "image/gif") {
console.log("Hello?");
let file = document.createElement('img');
file.setAttribute('src', reader.result);
figure.insertBefore(file, figCap);
} else if (i.type == "model/stl") {
console.log(`${i.name} is of type stl`, i);
} else {
log(`${i.name} is of type ${i.type} and is not supported`);
}*/
}
filesContainer.appendChild(figure)
reader.readAsDataURL(i)
}
}
Hope you guys can help.
Hi i Found out why it was doing so strange i had an file in my test collection that made the reader never finish so it never got the the part of if statement the fix i used is adding the reader.onload inside the if statement like this
if (i.type.match('image/png')) {
reader.onload = () => {
let img = document.createElement('img')
img.src = reader.result
figure.appendChild(img)
}
}