DEV Community

Michael Burrows
Michael Burrows

Posted on • Originally published at

How to get the file extension from an upload using JavaScript

This tutorial will help you understand the process involved in getting a file extension using JavaScript. If you’re building a web app that allows user file uploads this can be used to validate any file type restrictions you may want to implement.

Let’s get started by creating a form with a file input field, a button that’ll call a function to check the file extension, and a paragraph with a empty span that we’ll inject the file extension string inside once it has been established:

    <legend>Check file extension:</legend>
    <input type="file" id="input-file-upload" />
    <input type="button" id="btn-check-extension" value="Check" />
Enter fullscreen mode Exit fullscreen mode

Next the JavaScript starting with an event listener to detect when the button is clicked:

const btn = document.querySelector("#btn-check-extension");
btn.addEventListener('click', () => getExtension());
Enter fullscreen mode Exit fullscreen mode

This event listener then calls a getExtension function that looks like this:

const getExtension = () => {
  const file = document.querySelector("#input-file-upload").value;
  const extension = file.split(".").pop();
  document.querySelector("#result").textContent = extension;
Enter fullscreen mode Exit fullscreen mode

What we’re doing here is getting the filename from input field, using the split() method to split the filename and extension into an array, then using the pop() method which gets the last item from an array (the file extension).

That’s all for this tutorial. While you’re here why not check out some of these other JavaScript tutorials.

Top comments (0)