I want to POST multiple files and form variables to a CGI script, all in one HTTP request. I believe this requires a HTTP post with multipart/form-data
encoding. Here is a sample HTML form that sends the required information; I need to send the same information through the application:
<form action="/process.php" enctype="multipart/form-data" method="post">
<input type="text" name="foo" value="bar">
<input type="text" name="blah" value="baz">
<input type="file" name="file1">
<input type="file" name="file2">
<input type="file" name="file3">
</form>
Please note that the application is a C# .NET GUI (or console) application, not an ASP.Net application.
I had to do the same thing on a project last year. After some looking around, I found this:
Upload files with HTTPWebrequest (multipart/form-data)
The second answer in there should be what you're looking for. When I was trying to do this I ran into some trouble getting that exact method to work. The problem is that C#.NET does not have any support for multiple key/value pairs in a POST. So you must construct the HTTP request content header yourself. I believe the answer in the link above writes it directly to the request stream. I was able to convert the code found at the link below to build the header, and then wrote the bytes to the request stream.
http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/
My code looked something like the following (I've had to modify it below for readability because a lot of abstracted out as part of the whole project, so it may not be perfect syntactically).
Note that this only prepares a header for the upload of a single file.
I did this last year based upon some code that I found. It supports exactly what you want, both files and values.
Here is the class called
HttpForm
:You can use it like this:
Let me know if it works for you.