Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set the value of a type="file" input HTML element? [duplicate]

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?

like image 312
Juan Avatar asked May 16 '11 18:05

Juan


People also ask

How do I set the value of an input type file?

In HTML, we will use the type attribute to take input in a form and when we have to take the file as an input, the file value of the type attribute allows us to define an element for the file uploads.

How do I reset the input on a file?

Resetting a file input is possible and pretty easy with jQuery and HTML. For that purpose, you should wrap a <form> around <input type="file">, then call reset on the form by using the reset() method, then remove the form from the DOM by using the unwrap() method.

How does HTML input type file work?

A file input's value attribute contains a string that represents the path to the selected file(s). If no file is selected yet, the value is an empty string ( "" ). When the user selected multiple files, the value represents the first file in the list of files they selected.

How use input type file in React?

The file input Tag In HTML, an <input type="file"> lets the user choose one or more files from their device storage to be uploaded to a server or manipulated by JavaScript via the File API. Because its value is read-only, it is an uncontrolled component in React.


1 Answers

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.

like image 166
Chris Kooken Avatar answered Sep 23 '22 02:09

Chris Kooken