158

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)?

manji
  • 45,615
  • 4
  • 87
  • 100
marky
  • 4,261
  • 15
  • 50
  • 91
  • 11
    The browser changes the real path to `C:\fakepath\ ` so malicious sites can't use javascript to glean information about your computer's directory structure. – drudge Jun 16 '11 at 00:22

14 Answers14

310
var filename = $('input[type=file]').val().split('\\').pop();

or you could just do (because it's always C:\fakepath that is added for security reasons):

var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')
manji
  • 45,615
  • 4
  • 87
  • 100
  • 1
    Exactly what I needed, manji! I need to check the extension, too, so I used your example this way: var extension = filename.split('.').pop(); to get that, too! Thanks! – marky Jun 16 '11 at 00:29
  • Is it `Fakepath` with a capital F? – alex Jun 16 '11 at 00:31
  • It's lowercase `f`, but I changed my answer to replace with a `regexp+ignorecase flag`. – manji Jun 16 '11 at 00:36
  • 16
    @MikeDeSimone I've tested split('\\').pop(); on Win 7, Ubuntu 11.04 and Mac OS X and it works fine on all of them. – Alex Mar 08 '12 at 14:57
  • 3
    @Alex: Wow, that's pretty crazy. So it's really just a workaround for someone's bad JS code from way back that will never get fixed. I'm running Safari on a Mac, and I see "C:\fakepath\" in there. (Play with it in [jsfiddle](http://jsfiddle.net/daQD6/).) – Mike DeSimone Mar 08 '12 at 16:12
  • @MikeDeSimone: yeah, also I noticed in Ubuntu that $('input[type=file]').val(); gives you the file name and not the full (fake) path. – Alex Mar 08 '12 at 19:49
  • Bear in mind that if you use the first snippet (splitting on "\"), it'll break if there's a "\" on the filename. As it should always start with "C:\fakepath", the second option is more reliable IMHO – Vitor Baptista Apr 01 '14 at 23:42
  • 1
    @VítorBaptista Windows files cannot have backslashes in their names. It is possible on MacOS although _"You should avoid using colons and slashes in the names of files and folders because some operating systems and drive formats use these characters as directory separators"_ as described in [Apple's website](https://support.apple.com/en-us/HT202808) – joao.arruda Aug 28 '15 at 19:47
  • how can i achive if i have input file multiple? – Kim Ivan Bay-an Aug 03 '20 at 03:44
70

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 : "";
Diego Cotini
  • 989
  • 2
  • 15
  • 24
  • 1
    One thing to consider when using this option: when you click again on 'Choose file' button to bring up the open file window, then click on the escape button, a console error will be thrown. – luke_mclachlan Jan 15 '17 at 20:26
  • Yep, you are right, but the intention was putting just the code to get the name because as the code are getting the name from a hard coded position it would be necessary check if there is some file (an for this case we are talking in only one file, but could have more and the code would need to iterate by all elements). But sure, I'm going to update the code and include this validation. – Diego Cotini Jan 17 '17 at 13:11
23

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.

alex
  • 438,662
  • 188
  • 837
  • 957
21

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
Kotzilla
  • 1,083
  • 15
  • 23
  • The example code `var filename = $('input[type=file]').val().replace(/.*(\/|\\)/, '');` is using jQuery. – Zarepheth Aug 07 '13 at 17:50
14

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
Fortin
  • 151
  • 3
  • 14
bartlss
  • 151
  • 1
  • 2
  • Since the field ID does nothing in this context, The function in JS should have 1 parameter less, just e instead of fileSelect(id,e) just fileSelect(e). Thanks though for the solution :). – Jasper Lankhorst Jun 20 '17 at 09:42
8

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);
vafrcor
  • 81
  • 1
  • 1
5

How about something like this?

var pathArray = $('input[type=file]').val().split('\\');
alert(pathArray[pathArray.length - 1]);
Bertrand Marron
  • 19,324
  • 8
  • 52
  • 88
4

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

GolezTrol
  • 109,399
  • 12
  • 170
  • 196
3

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; 
} 
Paul Roub
  • 35,100
  • 27
  • 72
  • 83
3
<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>
Paul Karam
  • 3,252
  • 6
  • 27
  • 41
1
var filename=location.href.substr(location.href.lastIndexOf("/")+1);
alert(filename);
James A Mohler
  • 10,562
  • 14
  • 41
  • 65
1

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.');
});
Fischer Tirado
  • 161
  • 1
  • 5
1

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>
Debendra Dash
  • 3,944
  • 35
  • 32
0

We can also remove it using match

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