Thanks for the answers, everyone! I recently had to get this to work, and used your suggestions heavily. However, there were several complex parts that did not work as expected, mainly related to the actual inclusion of the file (which was an important part of the question). There are already many answers here, but I think this may be useful to someone in the future (I could not find many clear examples of this online). I wrote a blog post that explains this a bit more.
Basically, I first tried to transfer the file data as a UTF8 encoded string, but I had problems with the encoding files (it worked fine for a regular text file, but when loading a Word Document, for example, if I tried to save the file that was transferred to the published the form using Request.Files [0]. SaveAs () didnβt open the file in Word. I found that if you write the file data directly using Stream (most likely than StringBuilder), it worked as expected. Besides In addition, I made a couple of modifications that made my understanding easier.
By the way, the Multilateral Request for Forms for Comments and W3C Recommendation for mulitpart / form-data are some useful resources if someone needs a link for the specification.
I changed the WebHelpers class a little smaller and had simpler interfaces, now it is called FormUpload . If you pass FormUpload.FileParameter , you can pass the contents of the byte [] along with the file name and content type, and if you pass the string, it will treat it as a standard name / value combination.
Here is the FormUpload class:
// Implements multipart/form-data POST in C
Here is the call code that downloads the file and a few common message options:
// Read file data FileStream fs = new FileStream("c:\\people.doc", FileMode.Open, FileAccess.Read); byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); fs.Close(); // Generate post objects Dictionary<string, object> postParameters = new Dictionary<string, object>(); postParameters.Add("filename", "People.doc"); postParameters.Add("fileformat", "doc"); postParameters.Add("file", new FormUpload.FileParameter(data, "People.doc", "application/msword")); // Create request and receive response string postURL = "http://localhost"; string userAgent = "Someone"; HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters); // Process response StreamReader responseReader = new StreamReader(webResponse.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); webResponse.Close(); Response.Write(fullResponse);