Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
how to check if selected file type with FileReader

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
   }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!