Click here to Skip to main content
11,643,493 members (75,791 online)
Click here to Skip to main content

C# File Upload with form fields, cookies and headers

, 18 Apr 2010 CPOL 44.1K 30
Rate this:
Please Sign up or sign in to vote.
Full featured HTTP upload utility

In it's most basic form, uploading a file or other data to an HTTP form handler using managed code is quite simple using the System.Net.WebClient class.

Listing 1: SimpleWebClientUpload

public void SimpleWebClientUpload()
{
    string filePath = Path.GetFullPath("TestFiles/TextFile1.txt");
    var client = new WebClient();   
    client.UploadFile("http://localhost/myhandler.ashx", filePath);
}

It is a common case that some cookies need to be maintained between requests or perhaps a header needs to be added to the request. This is possible using the WebClient class but the technique is not immediately obvious.

The trick is to create a class that inherits WebClient and overrides WebClient.GetWebRequest.

You can then add your cookies or headers to the request before it is sent.

Listing 2: CustomWebClient

// usage example 

string filePath = Path.GetFullPath("TestFiles/TextFile1.txt");

// possibly an existing CookieContainer containing authentication
// or session cookies
var cookies = new CookieContainer();

var client = new CustomWebClient(cookies);

// existing cookies are sent
client.UploadFile(_postHandlerUri, filePath);

// cookies is an instance of a reference type so it now
// contains updated/new cookies resulting from the upload   

public class CustomWebClient : WebClient
{
    private CookieContainer _cookies;

    public CustomWebClient(CookieContainer cookies)
    {
        _cookies = cookies;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
        request.CookieContainer = _cookies;
        return request;
    }
}

If this fulfills your requirements, then you are good to go.

Unfortunately, most file upload scenarios are HTML form based and may contain form fields in addition to the file data. This is where WebClient falls flat. After review of the source code for WebClient, it is obvious that there is no possibility of reusing it to perform a file upload including additional form fields.

So, the only option is to create a custom implementation that conforms to rfc1867, rfc2388 and the W3C multipart/form-data specification that will enable file upload with additional form fields and exposes control of cookies and headers.

Enumeration of the details of the implementation are beyond the intended scope of this posting, but the references are linked above and the code is quite brief and clear so to those interested, the process should be clear.

Note: This class is an excerpt from a slightly larger library, Salient.Web.HttpLib.HttpRequestUtility, that contains, amongst other functionality, many convenience overloads that eliminate unused parameters you can see in the usage implementation.

Listing 3: Upload example usage

using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;

/// <span class="code-SummaryComment"><summary>
</span>

Listing 4: Upload.cs

// /*!
//  * Project: Salient.Web.HttpLib
//  * http://salient.codeplex.com
//  *
//  * Date: April 11 2010 
//  */

#region

using System;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using Microsoft.Win32;

#endregion

/// <span class="code-SummaryComment"><summary>
</span>

Using this class, you can easily post file data and form fields to form handlers and have full control of the cookies and headers that are sent/received.

Full implementation and tests can be found at http://salient.codeplex.com.

An alternate implementation of this code with a working Visual Studio 2008 solution can be found @ http://www.codeproject.com/KB/aspnet/Salient-Web-HttpLib-Intro.aspx.

History 

  • 04-18-2010 Removed licensing restriction 

License

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

Share

About the Author

Sky Sanders
Software Developer (Senior) Salient Solutions
United States United States
My name is Sky Sanders and I am an end-to-end, front-to-back software solutions architect with more than 20 years experience in IT infrastructure and software development, the last 10 years being focused primarily on the Microsoft .NET platform.

My motto is 'I solve problems.' and I am currently available for hire.

I can be contacted at sky.sanders@gmail.com

You may also be interested in...

Comments and Discussions

 
GeneralProgress Pin
Laserson26-Nov-10 0:22
memberLaserson26-Nov-10 0:22 
GeneralRe: Progress Pin
Sky Sanders26-Nov-10 0:25
memberSky Sanders26-Nov-10 0:25 
Not sure I understand your question. Can you elaborate?

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150731.1 | Last Updated 18 Apr 2010
Article Copyright 2010 by Sky Sanders
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid