Reputation: 5251
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?
Upvotes: 167
Views: 429643
Reputation: 648
Easy Path:
JQuery
$("#fileInputId").on("change", () => {
alert($("#fileInputId")[0].files[0].name);
});
JavaScript
document.getElementById("fileInputId").onchange = function() {
alert(document.getElementById("fileInputId").files[0].name)
};
Upvotes: 3
Reputation: 12584
var path = document.getElementById('upload').value;//take path
var tokens= path.split('\\');//split path
var filename = tokens[tokens.length-1];//take file name
Upvotes: 1
Reputation: 2619
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"
Upvotes: 252
Reputation: 3357
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>
Upvotes: 6
Reputation: 1901
Assuming:
<input type="file" name="file1" id="theFile">
The JavaScript would be:
var fileName = document.getElementById('theFile').files[0].name;
Upvotes: 29
Reputation: 6222
// 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
}
Upvotes: 2
Reputation: 189
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>
Upvotes: 0
Reputation: 2845
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:
With && nOffset+1 === str.length
added to isDirectory
:
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.
Upvotes: 5
Reputation: 2867
Nowadays there is a much simpler way:
var fileInput = document.getElementById('upload');
var filename = fileInput.files[0].name;
Upvotes: 178
Reputation: 25607
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];
Upvotes: 9
Reputation: 7228
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?
Upvotes: 3
Reputation: 11056
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);
}
Upvotes: 150
Reputation: 111047
var pieces = str.split('\\');
var filename = pieces[pieces.length-1];
Upvotes: 8