-1

I am using a custom file upload button in my web app. I want the user to see that they have chosen a file so I change the html of a div to show the file name.

Here is my jquery:

$("input[type=file]").change(function() {
    var filename = $("input[type=file]").val();
    $("#share-file-name p").html(filename);
});

Now, this works great, except for the fact that the value of the input is:

C:\fakepath\photo.jpg

So that's what the user sees. I just want them to see the "photo.jpg" part. How can I use my jquery to strip everything except for the file name?

Thanks!

user2320500
  • 169
  • 3
  • 10

5 Answers5

2

This should work:

filename = filename.replace(/^.*[\/\\]/, "");
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
1

You can just chop off anything to the left of the rightmost "/"

like so:

$("input[type=file]").change(function() {
    var filename = $("input[type=file]").val();
    // As pointed out in the comments, this line is required to make it
    // Windows compliant. It's important to handle paths from any OS.
    filename = filename.replace(/^.*[\\\/]/, '');
    $("#share-file-name p").html(filename);
});
SamHuckaby
  • 1,162
  • 1
  • 13
  • 35
1

If you have the full file path stored in a variable filename, you can do the following to get only the file name:

filename.substring(filename.lastIndexOf("\"))

Regular expressions or the split command are overkill for what you're trying to do.

Alex Kalicki
  • 1,533
  • 9
  • 20
0

use split("/"); and then you got an array with all elements separated by / so the last element will be the file name

var file = filepath.split("/"); file[file.length - 1] 
0

You can use this regular expression:

 filnameToDisplay = /([^\\]+.\w+$)/.exec(filename)[0];

This will get what you want regardless of length of the filepath or characters in the filename, unless they are using a strange extension I don't know about!

jahroy
  • 22,322
  • 9
  • 59
  • 108
Legion
  • 796
  • 7
  • 12