Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How to extract filename from a file input control

People also ask

How do I get the file extension of an input type file?

The full filename is first obtained by selecting the file input and getting its value property. This returns the filename as a string. By the help of split() method, we will split the filename into 2 parts. The first part will be the filename and the second part will be the extension of the file.

How do I find my upload file name?

Try document. getElementById("FileUpload1"). value this value should have a path for a file to be uploaded, just strip all dirs from that value and you will have file name.

How do I get real path instead of Fakepath?

Use IE with file protocol if you want to get the real path. Possible duplicate of How to get full path of selected file on change of <input type='file'> using javascript, jquery-ajax?


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"


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);
}

Nowadays there is a much simpler way:

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

Very simple

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

Assuming:

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

The JavaScript would be:

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

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