-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!

5
  • use regular expressions Commented Jul 9, 2013 at 21:24
  • use string manipulation, not jQuery. Commented Jul 9, 2013 at 21:28
  • doxdesk.com/img/updates/20091116-so-large.gif Commented Jul 9, 2013 at 21:28
  • filename.split('\').pop(); Commented Jul 9, 2013 at 21:29
  • Most of the answers below assume that all of your users are on Windows. The best answer is that which includes the regex '/[\/\\]/' which will work for all cases. Commented Jul 9, 2013 at 21:34

5 Answers 5

2

This should work:

filename = filename.replace(/^.*[\/\\]/, "");
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

4 Comments

doesn't work on windows, but hey it's only 90% of the market...
@dandavis which browser did you test it in that it didn't work? This is standard JavaScript, and it should work on all major browsers.
it's not the JS, it's the backwards path symbol that breaks...
Ah, you're quite right. I went ahead and fixed it, so it should work anywhere now.
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] 

Comments

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.