Javascript - How to extract filename from a file input control
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;
Related videos on Youtube
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 & Delphi. I also know Python and PowerBasic. Enough to get work done. ;)
Updated on December 05, 2020Comments
-
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 almost 15 yearsThis assumes that the user is running Windows. Other operating systems use different file path seperators.
-
Ian Oxley almost 15 yearsWould 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. almost 15 yearsIIRC, 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 almost 15 yearsThanks this seems to work well, but I just want filename without extension. How can I do that in above code.
-
Yogi Yang 007 almost 15 yearsI 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 almost 15 yearsstr.split(/(\\|\/)/g); for windows and *nix
-
Yeti almost 12 yearsNope, 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 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 about 10 yearsOddly 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 about 10 yearsWatch out for this path: dir.with.dots/fileWithoutDots as you will get eOffset less than nOffset and confuse the extraction expressions.
-
avngr about 9 yearshow to get the filenames in case of multiple file selection?
-
vog over 8 yearsYou can also do that just with regexes and without any array operation:
var filename = filepath.replace(/^.*?([^\\\/]*)$/, '$1');
-
nollidge over 8 yearsWhy not just calculate startIndex like so?
var startIndex = Math.max(fullPath.lastIndexOf('\\'), fullPath.lastIndexOf('/')) + 1;
-
Jon Watte almost 8 yearsvog'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 almost 8 yearsThis doesn't strip the extension, as asked for.
-
vog over 7 yearsFixed. Thanks for the hint!
-
vog over 7 years"a very simple regular expression" ... Well, actually these are two regexes. :-) See my answer for a single-regex solution.
-
vog over 7 yearsThe 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 over 7 yearsYes, 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 over 7 yearsI 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 over 7 yearsYeah, fixed it. Now that should work properly too (added
&& eOffset < nOffset
). -
Marc almost 7 yearsmultiplatform, concise. Great.
-
zeh about 6 yearsThis 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 almost 6 yearsCheck
fileInput.files.length
before calling.name
, in case the user clicked cancel. -
Morvael almost 6 yearsIn case you're using TypeScript then its $("#fileupload")[0]["files"][0];
-
Chatoxz over 4 yearsGreat solution, I don't understand how it work and that is why like it more!
-
FabricioG about 4 yearsval() would actually return the whole file path which is what he doesn't want.
-
wnm over 2 yearsI think the 'longer' regex version of
(\\|\/)
(vs the short[\\/]
) handles different path name syntax on different OSs, no? ItsC:\path\Filename.ext
on Windows, andhome/path/Filename.ext
on linux and macOs? -
Voxlinou about 2 yearsThat gives the entire path and not only the name which is not what OP is asking for.
-
Joe Johnston almost 2 yearsfwiw This works in 2022