DEV Community

Michael Burrows
Michael Burrows

Posted on • Originally published at w3collective.com

1

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:

<form>
  <fieldset>
    <legend>Check file extension:</legend>
    <input type="file" id="input-file-upload" />
    <input type="button" id="btn-check-extension" value="Check" />
  </fieldset>
</form>
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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay