Click here to Skip to main content
Licence CPOL
First Posted 1 Feb 2007
Views 74,505
Downloads 256
Bookmarked 21 times

Send a content type “multipart/form-data” request from C#

By | 5 Mar 2007 | Article
How to send a content type “multipart/form-data” request from C#.

Introduction

Here we will see a simple procedure to make a request of type "multipart/form-data" from C# using the HttpWebRequest class. We are taking this article as a reference: Send a request to an SSL page from C#.

Content

The big problem of this type of request is how to prepare the data package that will be passed to the class. For this, the more easy way to do is to make a string with the data in text form. You must be careful with this, because if you put the wrong character or separator, the package won't get to the destination successfully.

The next method makes this action about a parameters collection; these parameters can be of different types, because this way you can send the file content.

private string GetPostData() 
{ 
    string boundary = "--" + this._Boundary; 
    int arrReqs = this._ParamsCollection.Count * 5; 
    string[] auxReqBody = new string[arrReqs]; 
    int count = 0; 
    foreach(ParamsStruct par in this._ParamsCollection) 
    { 
        auxReqBody[count] = boundary; 
        count++; 
        switch (par.Type) 
        { 
            case ParamsStruct.ParamType.File: 
            { 
                auxReqBody[count] = "Content-Disposition: file; name=\"" + 
                   par.Name + "\"; filename=\"" + par.GetOnlyFileName() + "\""; 
                count++; 
                auxReqBody[count] = "Content-Type: text/plain"; 
                count++; 
                auxReqBody[count] = ""; 
                count++; 
                auxReqBody[count] = par.StringValue; 
                count++; 
                break; 
            } 
            case ParamsStruct.ParamType.Parameter: 
            default: 
            { 
                auxReqBody[count] = 
                  "Content-Disposition: form-data; name=\"" + par.Name + "\""; 
                count++; 
                auxReqBody[count] = ""; 
                count++; 
                auxReqBody[count] = par.StringValue; 
                count++; 
                break; 
            } 
        } 
    } 
    auxReqBody[count] = boundary; 
    count++; 
    string requestBody = String.Join("\r\n",auxReqBody); 
    return requestBody;
}

Then in the parameters collection, we have: a parameter of type "Parameter", name "param1", and value "param1Value", and another parameter of type "File", name "file", file name "fileName1.txt", and value "Content of fileName1.txt". After we run this method, you will obtain a text with this format:

--AaB03x\r\n 
Content-Disposition: form-data; name="param1"\r\n 
\r\n 
param1Value\r\n 
--AaB03x\r\n 
Content-Disposition: file; name="file"; filename="fileName1.txt"\r\n 
Content-Type: text/plain\r\n 
\r\n 
Content of fileName1.txt \r\n 
--AaB03x\r\n

After this, we will use a method similar to this one, for sending the information to the required page:

public void PostData ()
{ 
    //Set URL 
    Uri urlUri = new Uri(_URL); 
    //Encoding postData 
    ASCIIEncoding encoding = new ASCIIEncoding(); 
    string postData = this.GetPostData(); 
    byte[] buffer = encoding.GetBytes( postData ); 
    // Prepare web request... 
    HttpWebRequest myRequest = 
       (HttpWebRequest)WebRequest.Create(urlUri); 
    // We use POST ( we can also use GET ) 
    myRequest.Method = this._Method; 
    myRequest.AllowWriteStreamBuffering = true; 
    // Set the content type to a FORM 
    string auxContent = this._ContentType; 
    if (this._Boundary.Length > 0) 
        auxContent += "boundary=" + this._Boundary; 
    myRequest.ContentType = auxContent; 
    // Get length of content 
    myRequest.Accept = this._Accept; 
    myRequest.ContentLength = buffer.Length; 
    // Get request stream 
    Stream newStream = myRequest.GetRequestStream(); 
    // Send the data. 
    newStream.Write(buffer,0,buffer.Length); 
    // Close stream 
    newStream.Close(); 
    _myHttpWebResponse= (HttpWebResponse)myRequest.GetResponse(); 
    // Set the response to ResponseStream property 
    this._ResponseStream = _myHttpWebResponse.GetResponseStream();
}

For finishing this, we must process the request stream returned by the required page. In this case, I declare a property inside the class that transforms the response stream to a string.

public string ResponseString
{ 
    get 
    { 
        string resultData = ""; 
        StreamReader streamRead = new StreamReader( _ResponseStream ); 
        Char[] readBuffer = new Char[256]; 
        // Read from buffer 
        int count = streamRead.Read( readBuffer, 0, 256 ); 
        while (count > 0) 
        { 
            // get string 
            resultData += new String( readBuffer, 0, count); 
            // Write the data 
            Console.WriteLine( resultData ); 
            // Read from buffer 
            count = streamRead.Read( readBuffer, 0, 256); 
        } 
        // Release the response object resources. 
        streamRead.Close(); 
        return resultData; 
    }
}

In a simple way, this will adapt to another content type. Remember that the key is the form for loading the data package.

For SSL pages, see Send a request to an SSL page from C#.

License

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

About the Author

Pablo Russoniello

Web Developer

Argentina Argentina

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralDidn't Work :-(. Bad request exception (400) Pinmemberedazccode12:41 26 Nov '09  
GeneralSending Multiple image PinmemberMember 474402916:09 1 Apr '09  
General{"The operation has timed out"} PinmemberMichael Sync4:41 27 Aug '08  
Questionbinary data Pinmemberp. tj12:51 16 Apr '07  
AnswerRe: binary data Pinmemberstibstibstib0:26 7 Jun '07  
GeneralRe: binary data Pinmemberstibstibstib3:01 7 Jun '07  
As a reply to my previous post, this is what i have so far (in vb.net), think i must be pretty close
 
first i build the top part of my string and encode to byte array

postData = Boundary & newline
postData += "Content-Disposition: form-data; name=""form""" & newline & newline
postData += "submit" & newline & Boundary & newline
postData += "Content-Disposition: form-data; name=""externalVideoRef""" & newline & newline
postData += cVidRef & newline & Boundary & newline
postData += "Content-Disposition: form-data; name=""videoTitle""" & newline & newline
postData += cVidTitle & newline & Boundary & newline
postData += "Content-Disposition: form-data; name=""videoFile""" & newline
postData += "Content-Type:" & fileVideo.PostedFile.ContentType & newline & newline
 
data = encoding.GetBytes(postData)

 
i then attach the file to be uploaded to this byte array
 

Dim Buffer(4096) As Byte, BlockSize As Integer
Dim TempStream As New MemoryStream
Do
BlockSize = myFileStream.Read(Buffer, 0, 4096)
If BlockSize > 0 Then TempStream.Write(Buffer, 0, BlockSize)
Loop While BlockSize > 0
 
data2 = TempStream.ToArray()

 
I then join the two byte arrays together and close the Http POST request byte array

postData = newline & Boundary & newline
data3 = encoding.GetBytes(postData)
 
'return the complete binary data
Dim newArray(data.Length + data2.Length + data3.Length) As Byte
data.CopyTo(newArray, 0)
data2.CopyTo(newArray, data.Length)
data3.CopyTo(newArray, data.Length + data2.Length)

 

This is then sent normally as httpwebrequest object

 
myWebReq = WebRequest.Create(formUrl)
myWebReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; WindowsNT 5.1; SV1; .NET CLR 1.1.4322)"
myWebReq.Method = "POST"
myWebReq.ContentType = "multipart/form-data; boundary=" & Boundary
myWebReq.ContentLength = newArray.Length
 
Dim myStream As Stream = myWebReq.GetRequestStream()
myStream.Write(newArray, 0, newArray.Length)
myStream.Close()

 
its not quite there as the file doesnt get processed at the url location. am i missing something? any help would be gratefully appreciated!
QuestionRe: binary data(but how to code) Pinmemberwinart17:18 22 Jul '07  
GeneralAny difference to post file to JSP page Pinmembervdonthi8:26 6 Apr '07  
AnswerRe: Any difference to post file to JSP page PinmemberPablo Russoniello4:54 9 Apr '07  
Generalopen the POST request in a browser PinmemberZilberbal19:40 4 Mar '07  
AnswerRe: open the POST request in a browser PinmemberPablo Russoniello1:40 5 Mar '07  
GeneralRe: open the POST request in a browser PinmemberZilberbal0:17 8 Mar '07  
Questionhow to read xml data from a http post Pinmemberdeepa l12:16 22 Feb '07  
AnswerRe: how to read xml data from a http post PinmemberPablo Russoniello1:53 23 Feb '07  
Generalread xml data from a http post PinmemberMember #384406912:13 22 Feb '07  
QuestionTried to use your class Pinmemberalpha_krone21:13 21 Feb '07  
AnswerRe: Tried to use your class PinmemberPablo Russoniello1:31 22 Feb '07  
GeneralRe: Tried to use your class Pinmemberalpha_krone15:04 22 Feb '07  

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.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 5 Mar 2007
Article Copyright 2007 by Pablo Russoniello
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid