Click here to Skip to main content
11,489,574 members (65,720 online)
Click here to Skip to main content

UploadFileEx: C#'s WebClient.UploadFile with more functionality

, 19 Oct 2004 291.8K 3.7K 86
Rate this:
Please Sign up or sign in to vote.
UploadFile hides some of the things you might need to get your Windows client simulating forms with file input fields. UploadFileEx gives you more control where you need it!

Introduction

Okay, so you like the idea behind WebClient's UploadFile function, but you can't get it to do all the things you want? That's were I was at a week ago. This is what I learned in the past week. UploadFile seems good enough on the surface but you can run into some tricky things fast, like if you have some cookies to manage or you want to specify the content type, or change the name of the file input in the form? Well, this function will take care of those problems and should make simulating a web form with input type=file as easy as pi, er.. pie. Under the hood is a HttpWebRequest version of UploadFile that you could use to add additional functionality.

For example...

You would like to simulate this web form from your C# application:

<form action ="http://localhost/test.php" method = POST>
<input type = text name = uname>
<input type = password name =passwd>
<input type = FILE name = uploadfile>
<input type=submit>
</form>

You could run UploadFileEx like this:

CookieContainer cookies = new CookieContainer();
//add or use cookies
NameValueCollection querystring = new NameValueCollection();
querystring["uname"]="uname";
querystring["passwd"]="snake3";
string uploadfile;// set to file to upload
uploadfile = "c:\\test.jpg";

//everything except upload file and url can be left blank if needed
string outdata = UploadFileEx(uploadfile, 
     "http://localhost/test.php","uploadfile", "image/pjpeg", 
     querystring,cookies);

So on to the code...

So, this is UploadFileEx:

public static string UploadFileEx( string uploadfile, string url, 
    string fileFormName, string contenttype,NameValueCollection querystring, 
    CookieContainer cookies)
{
    if( (fileFormName== null) ||
        (fileFormName.Length ==0))
    {
        fileFormName = "file";
    }

    if( (contenttype== null) ||
        (contenttype.Length ==0))
    {
        contenttype = "application/octet-stream";
    }


    string postdata;
    postdata = "?";
    if (querystring!=null)
    {
        foreach(string key in querystring.Keys)
        {
            postdata+= key +"=" + querystring.Get(key)+"&";
        }
    }
    Uri uri = new Uri(url+postdata);


    string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
    HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
    webrequest.CookieContainer = cookies;
    webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
    webrequest.Method = "POST";


    // Build up the post message header
    StringBuilder sb = new StringBuilder();
    sb.Append("--");
    sb.Append(boundary);
    sb.Append("\r\n");
    sb.Append("Content-Disposition: form-data; name=\"");
    sb.Append(fileFormName);
    sb.Append("\"; filename=\"");
    sb.Append(Path.GetFileName(uploadfile));
    sb.Append("\"");
    sb.Append("\r\n");
    sb.Append("Content-Type: ");
    sb.Append(contenttype);
    sb.Append("\r\n");
    sb.Append("\r\n");            

    string postHeader = sb.ToString();
    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

    // Build the trailing boundary string as a byte array
    // ensuring the boundary appears on a line by itself
    byte[] boundaryBytes = 
           Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

    FileStream fileStream = new FileStream(uploadfile, 
                                FileMode.Open, FileAccess.Read);
    long length = postHeaderBytes.Length + fileStream.Length + 
                                           boundaryBytes.Length;
    webrequest.ContentLength = length;

    Stream requestStream = webrequest.GetRequestStream();

    // Write out our post header
    requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

    // Write out the file contents
    byte[] buffer = new Byte[checked((uint)Math.Min(4096, 
                             (int)fileStream.Length))];
    int bytesRead = 0;
    while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
        requestStream.Write(buffer, 0, bytesRead);

    // Write out the trailing boundary
    requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
    WebResponse responce = webrequest.GetResponse();
    Stream s = responce.GetResponseStream();
    StreamReader sr = new StreamReader(s);

    return sr.ReadToEnd();
}

This might help too..

You can handle the post in various ways but this is the PHP file I wrote to test:

<?php

print_r($_REQUEST);

$uploadDir = '%SOMEPATH';
$uploadFile = $uploadDir . $_FILES['userfile']['name'];
print "<PRE>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadFile))
{
    print "File is valid, and was successfully uploaded. ";
}
else
{
    print "Possible file upload attack!  Here's some debugging info:\n";
    print_r($_FILES);
}
print "</PRE>";
?>

Credits...

I found most of this out by trial and error searching the web. One major source of this information was this article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

madmik3

United States United States
No Biography provided

Comments and Discussions

 
BugUsing this code gave me 400 Bad request (malformed multipart POST) errors [Solved] Pin
Member 1027044710-Oct-13 11:22
memberMember 1027044710-Oct-13 11:22 
QuestionThanks for nice code but Length = 'requestStream.Length' threw an exception of type 'System.NotSupportedException' Pin
milindmorey9-Jul-13 4:16
membermilindmorey9-Jul-13 4:16 
Questionthanx Pin
Member 980996929-Apr-13 8:26
memberMember 980996929-Apr-13 8:26 
hiii...thanx a lot.its realy good.
but i tried with some pdf..it is not working . any solution please reply soon
my gmail is "ssojha1991@gmail.com"
Questionhelp, In VB.NET ?? Pin
mikrophun2-Jul-12 0:15
membermikrophun2-Jul-12 0:15 
AnswerRe: help, In VB.NET ?? Pin
clarkwgriswald26-Sep-13 6:43
memberclarkwgriswald26-Sep-13 6:43 
Questionany version in ASPX of PHP file ? Pin
kiquenet AE12-Dec-11 10:51
memberkiquenet AE12-Dec-11 10:51 
QuestionNot ok for videos file upload Pin
KKKT25-Jul-11 0:42
memberKKKT25-Jul-11 0:42 
GeneralHCG Ultra Pin
rmronimolic15-Jun-10 21:50
memberrmronimolic15-Jun-10 21:50 
QuestionDoes not work for me, where is my problem? Pin
Siedlerchr13-Nov-09 3:33
memberSiedlerchr13-Nov-09 3:33 
Generalcancel uploading Pin
djdane13-May-09 8:16
memberdjdane13-May-09 8:16 
GeneralRe: cancel uploading Pin
killix14-May-10 1:00
memberkillix14-May-10 1:00 
GeneralThanks Pin
shahid.here29-Apr-09 5:30
membershahid.here29-Apr-09 5:30 
GeneralNice but Pin
sabrown10024-Dec-08 5:42
membersabrown10024-Dec-08 5:42 
QuestionSending POST request to aspx pages [modified] Pin
cinni4-Dec-08 1:38
membercinni4-Dec-08 1:38 
GeneralUpload string + file + string Pin
Travelster661119-Oct-08 2:25
memberTravelster661119-Oct-08 2:25 
Generalform data and file upload Pin
syed wasif ali27-Jul-08 22:21
membersyed wasif ali27-Jul-08 22:21 
Generalmore files not only one file to upload Pin
kappos12-Jun-08 3:23
memberkappos12-Jun-08 3:23 
GeneralGracias excelente solucion Pin
Member 310478910-Jun-08 5:29
memberMember 310478910-Jun-08 5:29 
GeneralAs another commenter pointed out it's better to close the stream after you're done Pin
dolzenko1-Jun-08 9:01
memberdolzenko1-Jun-08 9:01 
GeneralAny one know how to decode this type of post Pin
smesser3-Jan-08 12:19
membersmesser3-Jan-08 12:19 
QuestiongetResponse like a web browser? Pin
Enderwiggin14-Dec-07 11:44
memberEnderwiggin14-Dec-07 11:44 
QuestionWhy it freezes sometimes at requestStream.Write(buffer, 0, bytesRead);? Pin
staryon14-Nov-07 8:31
memberstaryon14-Nov-07 8:31 
GeneralThanks Pin
creatorulcom5-Oct-07 13:11
membercreatorulcom5-Oct-07 13:11 
QuestionWebException Pin
tobi_z7-Sep-07 13:49
membertobi_z7-Sep-07 13:49 
QuestionHow to send a file a attachment Pin
PhBV3-Sep-07 3:50
memberPhBV3-Sep-07 3:50 
GeneralParse error in PHP page Pin
EdYellowMan22-May-07 5:20
memberEdYellowMan22-May-07 5:20 
GeneralGreat Job! Pin
kkkwkk17-May-07 5:11
memberkkkwkk17-May-07 5:11 
GeneralGet error in Tomcat Pin
franciscomesa28-Apr-07 5:00
memberfranciscomesa28-Apr-07 5:00 
GeneralRe: Get error in Tomcat Pin
craighack24-Jun-09 18:36
membercraighack24-Jun-09 18:36 
GeneralRe: Get error in Tomcat Pin
thikon_dew3-Jan-11 23:46
memberthikon_dew3-Jan-11 23:46 
Generalerrors Pin
Aaron Sulwer9-Aug-06 7:39
memberAaron Sulwer9-Aug-06 7:39 
GeneralIO.Exception, Cannot close stream until all bytes are written Pin
interesting.com.au27-Jul-06 21:15
memberinteresting.com.au27-Jul-06 21:15 
GeneralPlease Close() your files when done with them!!! Pin
Furroy19-Jul-06 5:45
memberFurroy19-Jul-06 5:45 
GeneralDid not work for me Pin
MRKKO17-May-06 7:26
memberMRKKO17-May-06 7:26 
GeneralRe: Did not work for me Pin
Mystic_20-May-06 4:59
memberMystic_20-May-06 4:59 
GeneralRe: Did not work for me Pin
Aaron Sulwer2-Aug-06 11:29
memberAaron Sulwer2-Aug-06 11:29 
Generalpost data to http://www.codeproject.com Pin
Mystic_27-Apr-06 22:06
memberMystic_27-Apr-06 22:06 
General2nd part Pin
Mystic_27-Apr-06 22:08
memberMystic_27-Apr-06 22:08 
QuestionGetting error as :(406) Not acceptable. Pin
Rahul.P7-Apr-06 0:42
memberRahul.P7-Apr-06 0:42 
GeneralWebClient with cookies now possible. Pin
katokay25-Mar-06 6:08
memberkatokay25-Mar-06 6:08 
GeneralRe: WebClient with cookies now possible. Pin
u7pro2-Mar-07 5:33
memberu7pro2-Mar-07 5:33 
GeneralRe: WebClient with cookies now possible. Pin
katokay2-Mar-07 6:28
memberkatokay2-Mar-07 6:28 
QuestionRe: WebClient with cookies now possible. Pin
NickHD22-Apr-07 3:28
memberNickHD22-Apr-07 3:28 
QuestionRe: WebClient with cookies now possible. Pin
Nooklez19-Jun-07 0:37
memberNooklez19-Jun-07 0:37 
AnswerRe: WebClient with cookies now possible. (Wrong) Pin
Absolute Solutions11-Jul-07 21:46
memberAbsolute Solutions11-Jul-07 21:46 
GeneralPOST data Pin
morecraf1-Mar-06 5:21
membermorecraf1-Mar-06 5:21 
GeneralRe: POST data Pin
satyajeeth20-Feb-07 2:01
membersatyajeeth20-Feb-07 2:01 
GeneralClosing Boundary Error Pin
Nick Lucas16-Dec-05 6:02
memberNick Lucas16-Dec-05 6:02 
GeneralRe: Closing Boundary Error Pin
Kartik Ganesan29-Nov-06 12:18
memberKartik Ganesan29-Nov-06 12:18 
GeneralProxy problems Pin
KriG23-Nov-05 3:02
memberKriG23-Nov-05 3:02 

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
Web01 | 2.8.150520.1 | Last Updated 20 Oct 2004
Article Copyright 2004 by madmik3
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid