0

I have a web page that is used to upload a file. There are two input fields on the form. One is of type text used to give the file a name in our database. The other is of type file to select the file to upload.

<input type="text" name="docName" id="docName" size="35" value="" />
<input type="file" name="importFile" id="importFile" size="35" onchange="refreshFileName();"/>

I want to use JavaScript to extract the actual file name (minus the file path) from the "importFile" field once it's selected and auto-populate the field "docName" with that value. My JavaScript looks like this:

function refreshFileName(){
var fileName = document.getElementById('importFile').value; 

var str = fileName.split("\\");
var length = str.length;

document.getElementById('docName').value = str[length-1]; 
}

This seems to work just file in Chrome, Firefox and IE 10 or 11. But it doesn't seem to work in IE 9 or earlier versions. Nothing I have tried seems to solve the problems. Any suggestions on how I can get this to work with earlier version of IE (I've already thought of the idea "just tell my users not to use IE").

Mike
  • 269
  • 3
  • 8
  • 20
  • Older IEs don't have indexable strings. – SLaks Mar 18 '14 at 14:39
  • You need to do some basic trouble shooting [(tutorial)](http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820) to see where it's failing. This at the very least involves `console.log()` to check your variables. – cookie monster Mar 18 '14 at 14:39
  • Tested in IE9, works fine. – adeneo Mar 18 '14 at 14:40
  • I just tested it in IE9. its working fine. – MARKAND Bhatt Mar 18 '14 at 14:42
  • 1
    `str` is an array of strings (or it should be), the result of `fileName.split()`. @Mike, try an alert(fileName) to see what you're getting. I cannot test in IE9 – Oscar Paz Mar 18 '14 at 14:42
  • Allready asked, and i think answered: [document.getElementById() returns null on IE9](http://stackoverflow.com/questions/8981337/document-getelementbyid-returns-null-on-ie9) and i found this as first result on google: [getElementById method](http://msdn.microsoft.com/en-us/library/ie/ms536437%28v=vs.85%29.aspx) Maybe one of those help you. – spitterfly Mar 18 '14 at 14:43

2 Answers2

0

You can use this: How to get the file name from a full path using JavaScript?

var fullPath = document.getElementById('importFile').value; 
var filename = fullPath.replace(/^.*[\\\/]/, '');

This solution is useful for Windows and Unix paths.

Community
  • 1
  • 1
Anton
  • 2,217
  • 3
  • 21
  • 34
0

If the problem is simply that you're getting back the full path in IE, try this:

var fileName = document.getElementById("importFile").value;
document.getElementById('docName').value = fileName.match(/[^\/\\]+$/);
ChrisF
  • 134,786
  • 31
  • 255
  • 325
Steve
  • 329
  • 1
  • 9