[javascript] Use jQuery to get the file input's selected filename without the path

I used this:

$('input[type=file]').val()

to get the file name selected, but it returned the full path, as in "C:\fakepath\filename.doc". The "fakepath" part was actually there - not sure if it's supposed to be, but this is my first time working with the filename of file uploads.

How can I just get the file name (filename.doc)?

This question is related to javascript jquery get filenames

The answer is


Get path work with all OS

var filename = $('input[type=file]').val().replace(/.*(\/|\\)/, '');

Example

C:\fakepath\filename.doc 
/var/fakepath/filename.doc

Both return

filename.doc
filename.doc

You just need to do the code below. The first [0] is to access the HTML element and second [0] is to access the first file of the file upload (I included a validation in case that there is no file):

    var filename = $('input[type=file]')[0].files.length ? ('input[type=file]')[0].files[0].name : "";

Here you can call like this Let this is my Input File control

  <input type="file" title="search image" id="file" name="file" onchange="show(this)"  />

Now here is my Jquery which get called once you select the file

<script type="text/javascript">
    function show(input) {
        var fileName = input.files[0].name;
        alert('The file "' + fileName + '" has been selected.');               
            }

</script>

<script type="text/javascript">

    $('#upload').on('change',function(){
       // output raw value of file input
       $('#filename').html($(this).val().replace(/.*(\/|\\)/, '')); 

        // or, manipulate it further with regex etc.
        var filename = $(this).val().replace(/.*(\/|\\)/, '');
        // .. do your magic

        $('#filename').html(filename);
    });
</script>

This alternative seems the most appropriate.

$('input[type="file"]').change(function(e){
        var fileName = e.target.files[0].name;
        alert('The file "' + fileName +  '" has been selected.');
});

var filename=location.href.substr(location.href.lastIndexOf("/")+1);
alert(filename);

How about something like this?

var pathArray = $('input[type=file]').val().split('\\');
alert(pathArray[pathArray.length - 1]);

Get the first file from the control and then get the name of the file, it will ignore the file path on Chrome, and also will make correction of path for IE browsers. On saving the file, you have to use System.io.Path.GetFileName method to get the file name only for IE browsers

var fileUpload    = $("#ContentPlaceHolder1_FileUpload_mediaFile").get(0); 
var files         =  fileUpload.files; 
var mediafilename = ""; 

for (var i = 0; i < files.length; i++) { 
  mediafilename = files[i].name; 
} 

We can also remove it using match

var fileName = $('input:file').val().match(/[^\\/]*$/)[0];
$('#file-name').val(fileName);

Chrome returns C:\fakepath\... for security reasons - a website should not be able to obtain information about your computer such as the path to a file on your computer.

To get just the filename portion of a string, you can use split()...

var file = path.split('\\').pop();

jsFiddle.

...or a regular expression...

var file = path.match(/\\([^\\]+)$/)[1];

jsFiddle.

...or lastIndexOf()...

var file = path.substr(path.lastIndexOf('\\') + 1);

jsFiddle.


Here is how I do it, it works pretty well.

In your HTML do:

<input type="file" name="Att_AttributeID" onchange="fileSelect(event)" class="inputField" />

Then in your js file create a simple function:

function fileSelect(id, e){
    console.log(e.target.files[0].name);
}

If you're doing multiple files, you should also be able to get the list by looping over this:

e.target.files[0].name

Does it have to be jquery? Or can you just use JavaScript's native yourpath.split("\\") to split the string to an array?


maybe some addition for avoid fakepath:

var fileName = $('input[type=file]').val();
var clean=fileName.split('\\').pop(); // clean from C:\fakepath OR C:\fake_path 
alert('clean file name : '+ fileName);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to get

Getting "TypeError: failed to fetch" when the request hasn't actually failed java, get set methods For Restful API, can GET method use json data? Swift GET request with parameters Sending a JSON to server and retrieving a JSON in return, without JQuery Retrofit and GET using parameters Correct way to pass multiple values for same parameter name in GET request How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list? Curl and PHP - how can I pass a json through curl by PUT,POST,GET Making href (anchor tag) request POST instead of GET?

Examples related to filenames

Rename multiple files in a folder, add a prefix (Windows) How to loop over files in directory and change path and add suffix to filename Why do I get a SyntaxError for a Unicode escape in my file path? Git copy file preserving history A html space is showing as %2520 instead of %20 How do I get the file name from a String containing the Absolute file path? DateTime.ToString() format that can be used in a filename or extension? Get only filename from url in php without any variable values which exist in the url Obtaining only the filename when using OpenFileDialog property "FileName" Build the full path filename in Python