Click here to Skip to main content
15,353,872 members
Articles / Web Development / HTML
Posted 28 Aug 2008


24 bookmarked

Setting a file to upload inside the WebBrowser component

Rate me:
Please Sign up or sign in to vote.
3.31/5 (9 votes)
28 Aug 2008CPOL3 min read
Changing the value of file input fields in WebBrowser made easy.


I needed to attach files silently to HTML forms hosted in a WebBrowser control without the user having to point to those files manually.

As you probably know, for security reasons, it is not possible to change the value of the HTML form file input programmatically. My first approach was to set focus on the input field and then do some SendKeys.SendWait() calls to set the value. The field can be hidden away from screen by setting the absolute position and negative coordinates for it. Although it had some drawbacks, it worked fine in a stand-alone app, but unfortunately, inside a Word add-in, file inputs cannot receive keyboard input for some reason.

After examining the methods of the WebBrowser, I found out that I can send arbitrary POST data using the Navigate() method:

WebBrowser.Navigate(Uri url, string targetFrameName, 
                    byte[] postData, string additionalHeaders)

There is a good example of how to make correct multipart request headers and body here, so I decided to use it. (You may also refer to RFC 1867.)

The solution: a helper class

To simplify the process of making requests, I wrote the helper class (included in the archive), so adding a file to the form can be as simple as:

private void webBrowser1_DocumentCompleted(object sender, 
             WebBrowserDocumentCompletedEventArgs e)
    HtmlElement form = webBrowser1.Document.Forms[0];
    form.AttachEventHandler("onsubmit", delegate(object o, EventArgs arg)
            FormToMultipartPostData postData = 
                new FormToMultipartPostData(webBrowser1, form);
            postData.SetFile("fileField", @"C:\windows\win.ini");

In the example above, I’m adding an event handler for the “onsubmit” event, which intercepts the submit process, prepares new multipart POST messages with the actual data in the form, attaches a file to the input field with a specific name (“fileField”), and then sends the result to the server (interrupting the original submit process).

Here’s a more complicated (and more correct) example, which manages several forms on one page (adding onsubmit handler only for forms with a “multipart/form-data” enctype attribute):

private void webBrowser1_DocumentCompleted(object sender, 
             WebBrowserDocumentCompletedEventArgs e)
    HtmlDocument doc = webBrowser1.Document;
    for (int i = 0; i < doc.Forms.Count; i++)
        // must be declared inside the loop because there's a closure
        HtmlElement form = doc.Forms[i];
        if (form.GetAttribute("enctype").ToLower() != "multipart/form-data") { continue; }
        form.AttachEventHandler("onsubmit", delegate(object o, EventArgs arg)
            FormToMultipartPostData postData = 
                new FormToMultipartPostData(webBrowser1, form);
            postData.SetFile("file", @"C:\windows\win.ini");
        form.SetAttribute("hasBrowserHandler", "1");
        // expose that we have a handler to JS

The FormToMultipartPostData class (not the best name, I know), which does all the ‘dirty’ work, must be instantiated just before submitting a form.

From the constructor, it loads all the values set in the form (GetValuesFromForm() method). The central method is GetEncodedPostData(), which returns all the necessary parameters to make a POST request with WebBrowser.Navigate() (header string and request body as a byte array). Submit() is another convenience method to invoke WebBrowser.Navigate() with the request data.

Because the class is rather large (compared to its modest functionality), I decided not to post it here. You can find it in the archive.

Handling JavaScript: form.submit()

By design, calling the submit() method on a form in JavaScript does not fire the onsubmit event, i.e., its handler will not be executed. To provide a work-around, I decided to set a handler for WebBrowser.Navigating, which is invoked before the page location is changed:

private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
    string url = e.Url.ToString();
    if (url.StartsWith("submit:"))
         string formId = url.Substring(7);
         HtmlElement form = webBrowser1.Document.GetElementById(formId);
         if (form != null) { form.RaiseEvent("onsubmit"); }
         e.Cancel = true;

The trick is to set the window location to fake the URL which starts with “submit:” (the rest of this “pseudo-URL” is the form ID). If anyone knows a more elegant solution, please share it with me.

You may have noted in the above “complicated example” of adding an onsubmit handler that there is an additional attribute to expose the presence of the handler to the JavaScript:

form.SetAttribute("hasBrowserHandler", "1");

Thus, the JavaScript code needed to invoke the submit process should be something like this:

function doSubmit(formId) {
  var form = document.getElementById(formId);
  if (form.getAttribute('hasBrowserHandler')) {
    window.location = "submit:" + formId;
  else {

The test script

I also included a PHP script which might be useful in testing and debugging the class.


Thanks to Steven Cheng from Microsoft, who posted an example of making multipart messages, I did not have to write the main (and most difficult) part of the code. There’s also an example of the same task done using the HttpWebRequest class on CodeProject.

I hope this solution will help you save some time (I spend a whole day to find the best way to solve this simple task.) Since at this time I am a newbie to C#, any feedback is appreciated.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Kirill Hryapin
Russian Federation Russian Federation
No Biography provided

Comments and Discussions

QuestionWhat if the user uses other programs that it does not affect Pin
cheddad201828-Feb-20 16:28
Membercheddad201828-Feb-20 16:28 
QuestionHow we can upload image automatically using webbrowser on and Pin
ashishgupta12121-Aug-13 2:13
Memberashishgupta12121-Aug-13 2:13 
SuggestionThis code without the JavaScript Pin
r-ISP20-Apr-13 11:20
professionalr-ISP20-Apr-13 11:20 
SuggestionRe: This code without the JavaScript Pin
r-ISP21-Apr-13 2:50
professionalr-ISP21-Apr-13 2:50 
QuestionThis Post is very helpul for me Pin
ashishgupta12129-Feb-13 13:35
Memberashishgupta12129-Feb-13 13:35 
AnswerRe: This Post is very helpul for me Pin
r-ISP26-Apr-13 8:04
professionalr-ISP26-Apr-13 8:04 
GeneralMy vote of 2 Pin
tyk3731-Aug-12 5:02
Membertyk3731-Aug-12 5:02 
QuestionpostData.setfile Pin
tyk3730-Aug-12 12:07
Membertyk3730-Aug-12 12:07 
QuestionAs if I want to use more than one file? Pin
lcsistemas19-Jul-12 21:14
Memberlcsistemas19-Jul-12 21:14 
QuestionConvert to Pin
NanoParedaz28-Jun-12 19:33
MemberNanoParedaz28-Jun-12 19:33 
SuggestionMissing bytes on the encoded data? Pin
olivax1-Mar-12 6:46
Memberolivax1-Mar-12 6:46 
GeneralRe: Missing bytes on the encoded data? Pin
Fernando JB18-Apr-13 9:15
MemberFernando JB18-Apr-13 9:15 
QuestionQuestion - webBrowser1_Navigating method Pin
donaldn200621-Feb-11 7:37
Memberdonaldn200621-Feb-11 7:37 
Questiontrying to get it to work - 3 questions Pin
donaldn200621-Feb-11 7:02
Memberdonaldn200621-Feb-11 7:02 
GeneralVB.NET code problem Pin
Member 450769726-May-10 7:46
MemberMember 450769726-May-10 7:46 
GeneralIt's work Pin
Wojciech Nagórski1-Oct-09 6:40
MemberWojciech Nagórski1-Oct-09 6:40 
Generalnot working... Pin
djdane14-May-09 4:45
Memberdjdane14-May-09 4:45 
QuestionHi Kirill Hryapin ( Code Project User ) Pin
kjhaveri26-Nov-08 19:49
Memberkjhaveri26-Nov-08 19:49 
GeneralCouldnt get it to work with particular URL Pin
Conker5-Oct-08 23:30
MemberConker5-Oct-08 23:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.