4

how to set textbox value based on uploaded filename value.for example i'm upload file like test.zip same value affect in text box the below code am try but not get solution?

var filename= document.getElementById("file").value;
    <form>
     File: <input type="file" id="file" name="file"/>
     Upload File : <input type="text" value="'+filename+'"/>
    </form>
javasundaram
  • 877
  • 2
  • 14
  • 28
  • possible duplicate of [Dynamically set value of a file input](http://stackoverflow.com/questions/1017224/dynamically-set-value-of-a-file-input) – Brigand Oct 16 '14 at 04:57
  • U need to use the files attribute to get the name – DarkBee Oct 16 '14 at 04:58

3 Answers3

2

Use some thing like this

  <script>
   function setfilename(val)
  {
    var fileName = val.substr(val.lastIndexOf("\\")+1, val.length);
   document.getElementById("filename").value = fileName;
  }
</script>
    <form>
     File: <input type="file" id="file" name="file" onchange="setfilename(this.value);"/>
     Upload File : <input type="text"  id="filename"/>
    </form>
Choco
  • 1,054
  • 1
  • 7
  • 20
2

You can get names of files by accessing files object of fileUpload like

document.getElementById("file").files[0].name

Assign this value to your text field onChange event of fileInput like this

document.getElementById("filename").value = document.getElementById("file").files[0].name;

will set first file name into your field with id filename

Getting value attribute of file input directly will get you fake file path like C:\fakepath\yourfilename.ext

user2009750
  • 3,169
  • 5
  • 35
  • 58
0

You need to listen onchange event of the file field and when it occurs you write the value to another text input.

var file = document.getElementById("file");
file.onchange = function() {
    document.getElementById('filename').value = file.value;
};

Where I set an id for the text field also:

Upload File : <input type="text" id="filename" value="'+filename+'"/>

However note, that the value you can retrieve from file input is not real but has a fake path due to security considerations. If you need only filename part of the full path you can split it by / character ad take the last piece.

dfsq
  • 191,768
  • 25
  • 236
  • 258