I have a HttpListenerRequest which was initiated from a html <form>
that was posted. I need to know how to get the posted form values + the uploaded files. Does anyone know of an example to save me the time doing it for myself? I've had a google around but not found anything of use.
The main thing to understand is that HttpListener is a low level tool to work with http requests. All post data is in HttpListenerRequest.InputStream stream. Suppose we have a form like that:
<form method=\"post\" enctype=\"multipart/form-data\"><input id=\"fileUp\" name=\"fileUpload\" type=\"file\" /><input type=\"submit\" /></form>
Now we want to see the post data. Lets implement a method to do this:
public static string GetRequestPostData(HttpListenerRequest request)
{
if (!request.HasEntityBody)
{
return null;
}
using (System.IO.Stream body = request.InputStream) // here we have data
{
using (var reader = new System.IO.StreamReader(body, request.ContentEncoding))
{
return reader.ReadToEnd();
}
}
}
upload some file and see result:
Content-Disposition: form-data; name="somename"; filename="D:\Test.bmp"
Content-Type: image/bmp
...here is the raw file data...
Next suppose we have simple form without uploading files:
<form method=\"post\">First name: <input type=\"text\" name=\"firstname\" /><br />Last name: <input type=\"text\" name=\"lastname\" /><input type=\"submit\" value=\"Submit\" /></form>
Let's see the output:
firstname=MyName&lastname=MyLastName
Combined form result:
Content-Disposition: form-data; name="firstname"
My Name
Content-Disposition: form-data; name="somename"; filename="D:\test.xls"
Content-Type: application/octet-stream
...raw file data...
As you can see in case of simple form you can just read InputStream to string and parse post values. If there is a more complex form - you need to perform more complex parsing but it's still can be done. Hope this examples will save your time. Note, that is not always the case to read all stream as a string.