This tutorial will help you understand the process involved in getting the file extension from an upload using JavaScript. If you’re building a web app that allows users to upload files 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>
<p>File extension: <span id="result"></span></p>
Code language: HTML, XML (xml)
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());
Code language: JavaScript (javascript)
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;
};
Code language: JavaScript (javascript)
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 all our JavaScript tutorials.