Javascript – How to extract filename from a file input control

Javascript – How to extract filename from a file input control

When a user selects a file in a web page I want to be able to extract just the filename.
I did try str.search function but it seems to fail when the file name is something like this: c:\uploads\ilike.this.file.jpg.
How can we extract just the file name without extension?

Solutions/Answers:

Solution 1:

Assuming your <input type=”file” > has an id of upload this should hopefully do the trick:

var fullPath = document.getElementById('upload').value;
if (fullPath) {
    var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
    var filename = fullPath.substring(startIndex);
    if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
        filename = filename.substring(1);
    }
    alert(filename);
}

Solution 2:

To split the string ({filepath}/{filename}) and get the file name you could use something like this:

str.split(/(\\|\/)/g).pop()

“The pop method removes the last element from an array and returns that
value to the caller.”
MOZILLA DEVELOPER NETWORK

Example:

from: "/home/user/file.txt".split(/(\\|\/)/g).pop()

you get: "file.txt"

Solution 3:

Nowadays there is a much simpler way:

var fileInput = document.getElementById('upload');   
var filename = fileInput.files[0].name;

Solution 4:

Very simple

let file = $("#fileupload")[0].files[0]; 
file.name

Solution 5:

Assuming:

<input type="file" name="file1" id="theFile">

The JavaScript would be:

var fileName = document.getElementById('theFile').files[0].name;

Solution 6:

var pieces = str.split('\\');
var filename = pieces[pieces.length-1];