javascript

JavaScript Snippet – Get File Extension from File Picker


When a user selects a file, you may need to know what type of file the user selected to decide how to handle the file.

<input id="fileInput" type="file">

<script>
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
  const fileName = this.files[0].name;
  const fileExt = fileName.split('.').pop();
  switch (fileExt) {
    case 'png':
      // handle .png files
      break;
    case 'jpg':
      // handle .jpg files
      break;
    case 'pdf':
      // handle .pdf files
    default:
      // handle any other file that doesn't match the cases above
      break;
  }
})
</script>

In JavaScript, you listen to the change event on the file input. You get the file name and call .split('.') on it. This creates a new array using “.” as a delimiter to split the string into the array. Calling .pop() on the resulting array returns the last item in the array, which will usually be the file extension.

You can then use a switch statement to check the file extension and determine what operation to perform.

Use Cases

  • Multiple file uploads

Share on social media

//