0

I have the following HTML / JS code:

<div class="file_upload">
        <input type="file" id="file_upload" name="file_upload" onchange="g();">
    </div>
<script>
    function g() {
        var fileName = document.getElementById("file_upload").value;
        fileName = fileName.substring(fileName.lastIndexOf('/')+1);
        alert(fileName);
    }
</script>

I want that after user upload a file, than the file name will displlay in alert the problem in this cide is that the path & the file name are diplayed and I want the file name only.

How can I fix it?

2
  • How does the path look like? You're searching for "/" but in Windows, for example, you have to search for "\". Commented Jul 13, 2013 at 9:59
  • Most likely you're testing on Windows and since the substring uses / to split off the filename, it won't match `\`. Quick solution would be: fileName = fileName.replace('\\', '/').substring(fileName.lastIndexOf('/') + 1); Commented Jul 13, 2013 at 9:59

1 Answer 1

1

Try with this:

var fnSplit = fileName.split(/[\/\\]/);
fileName = fnSplit[fnSplit.length - 1];

The path separator may be different with different OSes (for example, Windows and Linux), so you have to search for all of them. The most commons are / and \, and a simple regular expression can do the trick.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.