Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get File Name from Upload Form Using jQuery?

I want to get the file name of the uploaded file using jQuery. But the problem, I got the fake path and file name, instead of the file name only. This is my form.

<form action="" method="post">
   <input type="file" name="uploadFile" id="uploadFile" /> 
   <input type="submit" name="submit" value="Upload" id="inputSubmit" />
</form>

And the jQuery is like this

$(document).ready(function(){
    $('#inputSubmit').click(function(){
      alert($('#uploadFile').val());
    });
});

I use Chrome and got this in the alert box. Let's say I choose file named filename.jpg.

C:\fakepath\filename.jpg

How can I get only the file name? Thank you for your help.

like image 290
Abaij Avatar asked Sep 21 '11 13:09

Abaij


People also ask

How to get filename from file upload control in jQuery?

To select the file we will use HTML <input type=”file”>. After that we will get the file name by using the jQuery change() method. This method is used in the JQuery to get the file input by selected file name.

How do I get real path instead of Fakepath?

If you go to Internet Explorer; Tools; Internet Option; Security; Custom; find the "Include local directory path when uploading files to a server" (it is quite a ways down) and click on "Enable" You may have to restart your computer, but this works & eliminates that "fakepath" that inhibits the upload file path.

How check file is selected or not in jQuery?

length property in jQuery to check the file is selected or not. If element. files. length property returns 0 then the file is not selected otherwise file is selected.

How do you show the selected file name in react JS?

How do I get the input file name in React? React. js component : Click on the choose file button, select one file and it will print the details on console. We are using one loop and printing the following file properties : File.name : It returns the name of the file.


3 Answers

Split the filepath string with "\" and use the last item in the resulting array.

see: Getting the last element of a split string array

like image 198
Nathan Hase Avatar answered Sep 17 '22 20:09

Nathan Hase


You can also do:

$('#uploadFile').prop("files")['name'];

If it's a multiple file input, do:

$.each($('#uploadFile').prop("files"), function(k,v){
    var filename = v['name'];

    // filename = "blahblah.jpg", without path
});
like image 35
Mike Mackintosh Avatar answered Sep 17 '22 20:09

Mike Mackintosh


get file name when uploading using jquery

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

like image 35
ujjal Avatar answered Sep 17 '22 20:09

ujjal