0

How can I set the value of an input from a file type in a javaScript variable? this is my input:

<input type="file">
  • You mean the value of the input itsef (ie the filename) or the content of that file? – ibrahim mahrir Jul 14 '18 at 23:03
  • Not clear what your asking. Do you really want to set a variable with the value of the input? – Tibrogargan Jul 14 '18 at 23:03
  • Possible duplicate of [How do I get the value of text input field using JavaScript?](https://stackoverflow.com/questions/11563638/how-do-i-get-the-value-of-text-input-field-using-javascript) – Tibrogargan Jul 14 '18 at 23:04
  • 2
    The value of a `file` input can not be set programatically for security reasons. Getting the value after the user selects something, should be straight forward – adeneo Jul 14 '18 at 23:09
  • @ibrahimmahrir not the file name. for example you choose a picture by my input. and i want to set its source in a java script variable and use that variable later. –  Jul 14 '18 at 23:36
  • @Tibrogargan yes. i want to set its source in a java script variable and use that variable later. –  Jul 14 '18 at 23:37
  • Doesn't matter, the technique is exactly the same. That being said, you also have a `files` array on a file input that you can use, but for a single file input `value` is fine – Tibrogargan Jul 14 '18 at 23:39

2 Answers2

2

You can not set the value of a file input with Javascript.

The only way to set the value of a file input is by the user to select a file.

This is done for security reasons. Otherwise you would be able to create a Javascript that automatically uploads a specific file from the clients computer.

To get the value of a file input, use document.getElementById("fileinputid").value. However, it will give you the value mangled with something like c:\fakepath\ to keep the details of the user's filesystem private.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
-3

Setting the Value of the Input Element using JavaScript Variable

  document.addEventListener("DOMContentLoaded", function(event) {

    var input = document.getElementsByTagName('input');
    input[0].setAttribute("value", "c:\\yourPath\\");
    //The extra backslashes are to ignore each backslash

  });
<input type="file">