1

Here what I am getting is the full path of the input file but I need only the name of the selected file.

function change() {
  let fnVal = document.getElementById('fn').value;
  document.getElementById('file-name').innerHTML = fnVal;
}
<div>
  <input type="file" name="" id="fn" onchange="change();">
  <span id="file-name">File Name</span>
</div>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Kiran
  • 25
  • 5
  • You can rely on a filename not having a '/' or '\' in the title to find the file name. Figure out what folder separator the system is using, and do a `.split()` on that character, and get the last element in the array – TKoL Dec 11 '19 at 10:23
  • IE with file protocol? Just split by `/`, and take the last part. – Teemu Dec 11 '19 at 10:23

2 Answers2

1

A escaped backslash make a backslash in a string '\\'

So you will have to use .split("\\") to get the file name.

Try this:

function change() {
  let fnVal = document.getElementById('fn').value.split("\\");;
  document.getElementById('file-name').innerHTML = fnVal[fnVal.length - 1];
}
  <div><input type="file" name="" id="fn" onchange="change();"><span id="file-name">File Name</span></div>
Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51
0

Lets assume that you store full path name in fnVal like this;

let fnVal = 'path1/path2/path3/picture.jpg';

You can extract the only file name by splitting the path with this

let fileName = fnVal.split('/')[fnVal.split('/').length - 1]