Get Uploaded file extension in javascript

While working with files, sometimes we need to validate file extension or get file extension for independent use like display file based on extension. With HTML input, we can ask user to upload file to webpage.

Validating user input is necessary while file upload. It can be risky to enable user to upload all type of files to server. For that we can add client side or server side validation. But before implement, we need to get and specify file extension to enable upload.

In this tutorial, we will take file type input from user and display it's extension using regex and split & pop method. Here, we will take example for both methods.

Before starting let's add form and input with file type into out webpage. You can use existing form or element as per your requirement.


<form action="/fileupload.php">
    <input id="userFile" type="file" name="file">
    <button onclick="getExtension()">Get Extension</button>
</form>
<p id="displayExtension"></p>

Here, we have created form and added input with file type. We have also added empty paragraph tag with unique id. In further example, we will use this p tag to display extension of file.

Get File Extension Using Regex

The regex finds pattern into string and return response based on pattern. In files, name and extensions are divided by . and extension can not contain any special characters. So we will define our regex base on this logic.


function getExtension() {
    var fileInput = document.getElementById('userFile');
    var fileName = fileInput.files[0].name;

    var pattern = /\.([0-9a-z]+)(?:[\?#]|$)/i;
    var fileExtension = (fileName).match(pattern);
 
    document.getElementById('displayExtension').innerText = fileExtension;
}

In above example, first of all we have get file data using it's ID. Then defined regex pattern for finding extension and match it with file name. At last, we have displayed extension to user in empty paragraph tag.

Get File Extension Using Split and Pop Method

In this method, we will use split() to split string into array with dot. Then we will use pop() function to get last element from array which is extension of file.

Let's take example to understand it.


function getExtension() {
    var fileInput = document.getElementById('userFile');
    var fileName = fileInput.files[0].name;

    var fileExtension = fileName.split('.').pop();
 
    document.getElementById('displayExtension').innerText = fileExtension;
}

Here, we'll get file name just like previous method. Then split name extension into array and display user extension which last element of array.

Conclusion

In this article, we have taken simple example to get file extension. This example will get you file extension. Now on you can use extension for your requirement like validation or showing user message or more.


Share your thoughts

Ask anything about this examples