Get the filename from upload form using Javascript

I needed a way to access the filename of a file being uploaded or attached using the input file from a form. So, I created a nice little function to achieve this. Hopefully it comes in handy for someone.

<script type="text/javascript">
function getNameFromPath(strFilepath) {
    var objRE = new RegExp(/([^\/\\]+)$/);
    var strName = objRE.exec(strFilepath);

    if (strName == null) {
        return null;
    }
    else {
        return strName[0];
    }
}
</script>

11 comments for Get the filename from upload form using Javascript

Rod Smith's picture

Hi Richard This looks like...

Hi Richard
This looks like the function I require but maybe you can confirm...
I've produced a website for our local camera club and a few of us are uploading our pictures but the ftp process is a bit tricky for some less computerate users.
So I thought I'd use the html file upload on a basic form for them.
Unfortunately when they select a file it only shows the first part of the path and they're not sure it's the correct picture. I'd like to show just the filename, (and extension), below the select field so they can be sure about what they are uploading.
I know I can't check filesizes for them with javascript but could I check that the name fits our layout? Basically I'm telling everyone to call their pictures p1.jpg, p2.jpg etc so they drop into the gallery in the right place.
Many Thanks
ROD

Richard Castera's picture

Hey Rod, Sorry it took so...

Hey Rod,

Sorry it took so long to reply. Yes this is what you are looking for. It will display the filename of the file they want to upload.

Daniel Messano's picture

Thank you. Given enough time...

Thank you. Given enough time I could have come up with something like this, but i don't need to because you did Smile

Richard Castera's picture

No worries! Happy it worked...

No worries! Happy it worked out for you!

Naveen's picture

Thank you Richard. This came...

Thank you Richard.
This came in handy for me!

Richard Castera's picture

Awesome!...

Awesome!

Om Shanker Mishra's picture

Thanks Its Very useful code!...

Thanks Its Very useful code!

Espen Overaae's picture

Thanks for this, makes my day...

Thanks for this, makes my day a little more pleasant Smile

Bijoy Padhi's picture

Good work. Works very well!...

Good work. Works very well!

Anonymous's picture

Thanks a lot good work......

Thanks a lot good work... Smile

may_tinhhong's picture

Thanks so much. It's useful...

Thanks so much. It's useful for me!

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.