Javascript - How to extract filename from a file input control

340,219

Solution 1

Assuming your <input type="file" > has an id of upload this should hopefully do the trick:

var fullPath = document.getElementById('upload').value;
if (fullPath) {
    var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
    var filename = fullPath.substring(startIndex);
    if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
        filename = filename.substring(1);
    }
    alert(filename);
}

Solution 2

To split the string ({filepath}/{filename}) and get the file name you could use something like this:

str.split(/(\\|\/)/g).pop()

"The pop method removes the last element from an array and returns that value to the caller."
Mozilla Developer Network

Example:

from: "/home/user/file.txt".split(/(\\|\/)/g).pop()

you get: "file.txt"

Solution 3

Nowadays there is a much simpler way:

var fileInput = document.getElementById('upload');   
var filename = fileInput.files[0].name;

Solution 4

Very simple

let file = $("#fileupload")[0].files[0]; 
file.name

Solution 5

Assuming:

<input type="file" name="file1" id="theFile">

The JavaScript would be:

var fileName = document.getElementById('theFile').files[0].name;
Share:
340,219

Related videos on Youtube

Yogi Yang 007
Author by

Yogi Yang 007

I am a software developer and I learn a lot from other peoples work and by observing. I work on part-time basis as a consultant to Software developing companies. I have mastery in UI designing, I have got good hold on VB6, Delphi, VB.NET, PHP, RealBASIC, PureBasic, C#, KBasic &amp; Delphi. I also know Python and PowerBasic. Enough to get work done. ;)

Updated on December 05, 2020

Comments

  • Yogi Yang 007
    Yogi Yang 007 over 3 years

    When a user selects a file in a web page I want to be able to extract just the filename.

    I did try str.search function but it seems to fail when the file name is something like this: c:\uploads\ilike.this.file.jpg.

    How can we extract just the file name without extension?

  • Quentin
    Quentin almost 15 years
    This assumes that the user is running Windows. Other operating systems use different file path seperators.
  • Ian Oxley
    Ian Oxley almost 15 years
    Would you need to check for the '/' character as well for non-Windows users e.g. if (!pieces) { str.split('/'); }? Nice simple solution though +1
  • TM.
    TM. almost 15 years
    IIRC, IE is the only browser that gives the full path of the file anyway... You won't need to split on other browsers like Firefox, so it still works. Although I admit I haven't tried EVERY linux/unix browser.
  • Yogi Yang 007
    Yogi Yang 007 almost 15 years
    Thanks this seems to work well, but I just want filename without extension. How can I do that in above code.
  • Yogi Yang 007
    Yogi Yang 007 almost 15 years
    I added these two lines of code to extract just the file name without extension: "filename = filename.substring(0,filename.length-4); filename = filename.toLowerCase();"
  • Tracker1
    Tracker1 almost 15 years
    str.split(/(\\|\/)/g); for windows and *nix
  • Yeti
    Yeti almost 12 years
    Nope, you don't want to do it that way Yogi Yang says. Instead use: filename = filename.substring(0, filename.lastIndexOf('.')); Because his way will fail with extensions of more characters than 3, thus: .html, .jpeg etc.
  • lededje
    lededje over 11 years
    @TM. Chrome uses a fake path variable for safety which is ugly; iirc it is different depending on what OS you are on.
  • Jesse Chisholm
    Jesse Chisholm about 10 years
    Oddly enough, it is only the Windows user interface and compilers that care whether you use "\" or "/" for directory separator. The internal Win32 and kernel libraries treat them the same.
  • Jesse Chisholm
    Jesse Chisholm about 10 years
    Watch out for this path: dir.with.dots/fileWithoutDots as you will get eOffset less than nOffset and confuse the extraction expressions.
  • avngr
    avngr about 9 years
    how to get the filenames in case of multiple file selection?
  • vog
    vog over 8 years
    You can also do that just with regexes and without any array operation: var filename = filepath.replace(/^.*?([^\\\/]*)$/, '$1');
  • nollidge
    nollidge over 8 years
    Why not just calculate startIndex like so? var startIndex = Math.max(fullPath.lastIndexOf('\\'), fullPath.lastIndexOf('/')) + 1;
  • Jon Watte
    Jon Watte almost 8 years
    vog's answer is really close to the 100% accurate answer to the question (except needs to strip the extension.) A filename is no different from any other string.
  • Jon Watte
    Jon Watte almost 8 years
    This doesn't strip the extension, as asked for.
  • vog
    vog over 7 years
    Fixed. Thanks for the hint!
  • vog
    vog over 7 years
    "a very simple regular expression" ... Well, actually these are two regexes. :-) See my answer for a single-regex solution.
  • vog
    vog over 7 years
    The split regex can be shortened to [\\/]. Moreover, it was asked for stripping the file extension, too. For a complete solution, see: stackoverflow.com/a/32156800/19163
  • Jon Watte
    Jon Watte over 7 years
    Yes, there is also an obvious re-write to pack those two regexes into a single regex using the pipe (|) operator. I think the code as written is clearer, but it does run through the string twice, which would be a problem if the string is generally pretty long. (File paths typically aren't, but can be.)
  • vog
    vog over 7 years
    I was just nitpicking. Please don't take that seriously. There is no need to optimize, all proposed solutions are more than fast enough. Very long file paths are still kilobytes, not gigabytes. And this function will be triggered once per file upload, not 1000x in a batch. The only things that matter here are correctness and clarity of the code.
  • Yeti
    Yeti over 7 years
    Yeah, fixed it. Now that should work properly too (added && eOffset < nOffset).
  • Marc
    Marc almost 7 years
    multiplatform, concise. Great.
  • zeh
    zeh about 6 years
    This misses an important part of the question, "extract just the file name without extension". It helps to read the question carefully first before jumping to answer it.
  • marcovtwout
    marcovtwout almost 6 years
    Check fileInput.files.length before calling .name, in case the user clicked cancel.
  • Morvael
    Morvael almost 6 years
    In case you're using TypeScript then its $("#fileupload")[0]["files"][0];
  • Chatoxz
    Chatoxz over 4 years
    Great solution, I don't understand how it work and that is why like it more!
  • FabricioG
    FabricioG about 4 years
    val() would actually return the whole file path which is what he doesn't want.
  • wnm
    wnm over 2 years
    I think the 'longer' regex version of (\\|\/) (vs the short [\\/]) handles different path name syntax on different OSs, no? Its C:\path\Filename.exton Windows, and home/path/Filename.exton linux and macOs?
  • Voxlinou
    Voxlinou about 2 years
    That gives the entire path and not only the name which is not what OP is asking for.
  • Joe Johnston
    Joe Johnston almost 2 years
    fwiw This works in 2022