Today I needed to be able to POST multipart/form-data to a form in order to submit for values as well as upload a file. All using HTTP POST.
The first step was finding out that there does not seem to be a native way to post both form parameter and upload a file together. WebClient.UploadValues allows for the parameter name/value pairs, but sets it’s encoding type to application/x-www-form-urlencoded which is incorrect for file uploads. The code for this would look something like this:
Dim data As New NameValueCollection(); data.Add("id", "10") data.Add("param", "content") data.Add("file", "A0BA") Dim client As New WebClient client.UploadValues("http://my.test.address.com/", null, data)
I found that WebClient.UploadFile does set content type to multipart/form-data, *BUT* there is no way to post parameters, and the request is not properly formatted. To clarify, it will work fine with a IIS webserver, but any other real webserver (Apache, Tomcat) would choke on the malformed output. Microsoft does not do standards too well if you have not noticed. Microsoft — if you are reading this, kindly go read RFC1867. The call would look like this
Dim client As New WebClient client.UploadFile("http://my.test.address.com/", null, "c:\test.txt");
My main issue is not the incompatibility in this instance, but rather that I cannot post parameters and the file in the same post.
In order to solve this, I found a excellent class written by Gregory Prentice. I compiled the c# class and included a reference to it in my vb.net app. Then it was a simple matter of adding the reference Imports Helpers and adding this code:
Dim form As New MultipartForm("http://path.to.my.form/form.aspx") form.SetField("id", "10") form.SetField("param", "content") form.SendFile("C:\filepath.txt")
And booyah it works!
Additional Link Dump:
Uploading a file over HTTP in .NET
Three ways to use C# within a VB.NET project
System.Net.WebClient Class
How to post a file via HTTP post in vb.net
Upload files with HTTPWebrequest (multipart/form-data)