16

Note:

The answer(s) below reflect the state of legacy browsers in 2009. Now you can actually set the value of the file input element dynamically/programatically using JavaScript in 2017.

See the answer in this question for details as well as a demo:
How to set file input value programatically (i.e.: when drag-dropping files)?

What I need to do is to programmatically send a POST request to a service from javascript code from an application that uses a .NET WebBrowser, which is basically an embedded Internet Explorer. This service requires one of the fields to be a "file".

So either, is there any way to set the value of a "file" input in a form, given that I have the content of the file, such as in an array of bytes (and not the path of the file; I'm not trying to steal files from users here :) ).

Or perhaps a way to explicitly create and send the POST request instead of creating a FORM dynamically?

I need to use JavaScript code that will be run in my WebBrowser (think IE). Is this possible?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Juan
  • 15,274
  • 23
  • 105
  • 187
  • http://stackoverflow.com/questions/1696877/how-to-set-a-value-to-a-file-input-in-html – Sami Apr 04 '13 at 12:44

1 Answers1

16

Unfortunately this is not possible as it would be a security issue. Javascript control over file input fields is very limited. Otherwise people could use this to steal files from user's computers.

Since you have control over the browser, you can send the file using a normal HTTPWebRequest, but it can't be done in JavaScript.

Chris Kooken
  • 32,730
  • 15
  • 85
  • 123
  • This is a .NET application with an embedded web browser... Technically you can use `HttpWebRequest` or in fact just upload it directly over FTP :) – mellamokb May 16 '11 at 18:15
  • 1
    Even if I have access to the content of the file from my javascript code? (The contents, not just the path). – Juan May 16 '11 at 18:15
  • Yea, i was in the process of adding that to my answer – Chris Kooken May 16 '11 at 18:15
  • You would need to look up the raw format that data is sent for a File Post, and construct it yourself. – mellamokb May 16 '11 at 18:16
  • @jsoldi if you have access to the content, and it is textual. You can read the contents into a variable and post it to the server as a string. – Chris Kooken May 16 '11 at 18:16
  • @mellamokb: So then, is possible, even if hard, to construct the POST myself from javascript? @Chris: That's kinda my question, any clue how to get started with that? – Juan May 16 '11 at 18:17
  • @Chris: The server probably expects a file upload and OP wants to interface with a third-party server. – mellamokb May 16 '11 at 18:17
  • @jsoldi: It seems technically like it would be possible, using for instance jQuery's `$.POST` toolset. – mellamokb May 16 '11 at 18:17
  • http://stackoverflow.com/questions/1696877/how-to-set-a-value-to-a-file-input-in-html – Sami Apr 04 '13 at 12:44