Javascript - How to extract filename from a file input control
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?
Solution 1:
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:
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:
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