Javascript - How to extract filename from a file input control

JavascriptBrowserExtract

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 2 - Javascript

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 3 - Javascript

Nowadays there is a much simpler way:

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

Solution 4 - Javascript

Very simple

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

Solution 5 - Javascript

Assuming:

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

The JavaScript would be:

var fileName = document.getElementById('theFile').files[0].name;

Solution 6 - Javascript

var pieces = str.split('\\');
var filename = pieces[pieces.length-1];

Solution 7 - Javascript

I assume you want to strip all extensions, i.e. /tmp/test/somefile.tar.gz to somefile.

Direct approach with regex:

var filename = filepath.match(/^.*?([^\\/.]*)[^\\/]*$/)[1];

Alternative approach with regex and array operation:

var filename = filepath.split(/[\\/]/g).pop().split('.')[0];

Solution 8 - Javascript

Input: C:\path\Filename.ext
Output: Filename

In HTML code, set the File onChange value like this...

<input type="file" name="formdata" id="formdata" onchange="setfilename(this.value)"/>

Assuming your textfield id is 'wpName'...

<input type="text" name="wpName" id="wpName">

JavaScript

<script>
  function setfilename(val)
  {
    filename = val.split('\\').pop().split('/').pop();
	filename = filename.substring(0, filename.lastIndexOf('.'));
	document.getElementById('wpName').value = filename;
  }
</script>

Solution 9 - Javascript

I just made my own version of this. My function can be used to extract whatever you want from it, if you don't need all of it, then you can easily remove some code.

<html>
<body>
<script type="text/javascript">
// Useful function to separate path name and extension from full path string
function pathToFile(str)
{
    var nOffset = Math.max(0, Math.max(str.lastIndexOf('\\'), str.lastIndexOf('/')));
    var eOffset = str.lastIndexOf('.');
    if(eOffset < 0 && eOffset < nOffset)
    {
        eOffset = str.length;
    }
    return {isDirectory: eOffset === str.length, // Optionally: && nOffset+1 === str.length if trailing slash means dir, and otherwise always file
            path: str.substring(0, nOffset),
            name: str.substring(nOffset > 0 ? nOffset + 1 : nOffset, eOffset),
            extension: str.substring(eOffset > 0 ? eOffset + 1 : eOffset, str.length)};
}

// Testing the function
var testcases = [
    "C:\\blabla\\blaeobuaeu\\testcase1.jpeg",
    "/tmp/blabla/testcase2.png",
    "testcase3.htm",
    "C:\\Testcase4", "/dir.with.dots/fileWithoutDots",
    "/dir.with.dots/another.dir/"
];
for(var i=0;i<testcases.length;i++)
{
    var file = pathToFile(testcases[i]);
    document.write("- " + (file.isDirectory ? "Directory" : "File") + " with name '" + file.name + "' has extension: '" + file.extension + "' is in directory: '" + file.path + "'<br />");
}
</script>
</body>
</html>

Will output the following:

  • File with name 'testcase1' has extension: 'jpeg' is in directory: 'C:\blabla\blaeobuaeu'
  • File with name 'testcase2' has extension: 'png' is in directory: '/tmp/blabla'
  • File with name 'testcase3' has extension: 'htm' is in directory: ''
  • Directory with name 'Testcase4' has extension: '' is in directory: 'C:'
  • Directory with name 'fileWithoutDots' has extension: '' is in directory: '/dir.with.dots'
  • Directory with name '' has extension: '' is in directory: '/dir.with.dots/another.dir'

With && nOffset+1 === str.length added to isDirectory:

  • File with name 'testcase1' has extension: 'jpeg' is in directory: 'C:\blabla\blaeobuaeu'
  • File with name 'testcase2' has extension: 'png' is in directory: '/tmp/blabla'
  • File with name 'testcase3' has extension: 'htm' is in directory: ''
  • Directory with name 'Testcase4' has extension: '' is in directory: 'C:'
  • Directory with name 'fileWithoutDots' has extension: '' is in directory: '/dir.with.dots'
  • Directory with name '' has extension: '' is in directory: '/dir.with.dots/another.dir'

Given the testcases you can see this function works quite robustly compared to the other proposed methods here.

Note for newbies about the \\: \ is an escape character, for example \n means a newline and \t a tab. To make it possible to write \n, you must actually type \\n.

Solution 10 - Javascript

Neither of the highly upvoted answers actually provide "just the file name without extension" and the other solutions are way too much code for such a simple job.

I think this should be a one-liner to any JavaScript programmer. It's a very simple regular expression:

function basename(prevname) {
    return prevname.replace(/^(.*[/\\])?/, '').replace(/(\.[^.]*)$/, '');
}

First, strip anything up to the last slash, if present.

Then, strip anything after the last period, if present.

It's simple, it's robust, it implements exactly what's asked for. Am I missing something?

Solution 11 - Javascript

// HTML
<input type="file" onchange="getFileName(this)">

// JS
function getFileName(input) {
    console.log(input.files[0].name) // With extension
    console.log(input.files[0].name.replace(/\.[^/.]+$/, '')) // Without extension
}

How to remove the extension

Solution 12 - Javascript

var path = document.getElementById('upload').value;//take path
var tokens= path.split('\\');//split path
var filename = tokens[tokens.length-1];//take file name

Solution 13 - Javascript

None of the above answers worked for me, here is my solution which updates a disabled input with the filename:

<script type="text/javascript"> 
  document.getElementById('img_name').onchange = function () {
  var filePath = this.value;
    if (filePath) {
      var fileName = filePath.replace(/^.*?([^\\\/]*)$/, '$1');
      document.getElementById('img_name_input').value = fileName;
    }
  };
</script>

Solution 14 - Javascript

//x=address or src
if(x.includes('/')==true){xp=x.split('/')} //split address
if(x.includes('\\')==true){xp=x.split('\\')} //split address
xl=xp.length*1-1;xn=xp[xl] //file==xn
xo=xn.split('.'); //file parts=xo
if(xo.lenght>2){xol=xo.length-1;xt=xo[xol];xr=xo.splice(xol,1);
xr=xr.join('.'); // multiple . in name
}else{
xr=xo[0]; //filename=xr
xt=xo[1]; //file ext=xt
}
xp.splice(xl,1); //remove file
xf=xp.join('/'); //folder=xf , also corrects slashes

//result
alert("filepath: "+x+"\n folder: "+xf+"("+xl+")\n file: "+xn+"\n filename: "+xr+"\n .ext:  "+xt)

Solution 15 - Javascript

If you are using jQuery then

$("#fileupload").val();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYogi Yang 007View Question on Stackoverflow
Solution 1 - JavascriptVallaDangerView Answer on Stackoverflow
Solution 2 - JavascriptIan OxleyView Answer on Stackoverflow
Solution 3 - Javascriptmaxime schoeniView Answer on Stackoverflow
Solution 4 - JavascriptUchennaView Answer on Stackoverflow
Solution 5 - JavascriptXedretView Answer on Stackoverflow
Solution 6 - JavascriptTM.View Answer on Stackoverflow
Solution 7 - JavascriptvogView Answer on Stackoverflow
Solution 8 - JavascriptDxTxView Answer on Stackoverflow
Solution 9 - JavascriptYetiView Answer on Stackoverflow
Solution 10 - JavascriptJon WatteView Answer on Stackoverflow
Solution 11 - JavascriptMikelView Answer on Stackoverflow
Solution 12 - JavascriptLuca C.View Answer on Stackoverflow
Solution 13 - JavascriptsigiView Answer on Stackoverflow
Solution 14 - JavascriptcoolplaysView Answer on Stackoverflow
Solution 15 - JavascriptRajat BansalView Answer on Stackoverflow