Question

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?

Was it helpful?

Solution

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);
}

OTHER TIPS

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"

Nowadays there is a much simpler way:

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

Very simple

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

Assuming:

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

The JavaScript would be:

var fileName = document.getElementById('theFile').files[0].name;
var pieces = str.split('\\');
var filename = pieces[pieces.length-1];

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.

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];

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>

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?

// 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

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>

If you are using jQuery then

$("#fileupload").val();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top