{"id":107,"date":"2011-06-11T21:27:20","date_gmt":"2011-06-11T13:27:20","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=107"},"modified":"2018-09-22T15:58:59","modified_gmt":"2018-09-22T07:58:59","slug":"sending-a-file-and-some-form-data-via-http-post-in-c","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/sending-a-file-and-some-form-data-via-http-post-in-c\/","title":{"rendered":"Sending a file and some form data via HTTP post in C#"},"content":{"rendered":"<p>A few weeks back, I wrote some logic to send a file and a from a windows client over to a Java server endpoint. There are a few ways to do that: via application protocols like FTP and <a href=\"https:\/\/www.techcoil.com\/glossary\/http\/\" rel=\"noopener\" target=\"_blank\">HTTP<\/a> or even implementing a custom protocol using TCP\/IP. Since the Java server was already <a title=\"A mechanism for serving HTTP requests in C#\" href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/a-mechanism-for-serving-http-requests-in-c\/\" target=\"_blank\">serving HTTP requests<\/a> and that <a href=\"https:\/\/www.techcoil.com\/glossary\/http-request\/\" rel=\"noopener\" target=\"_blank\">HTTP requests<\/a> can usually get through firewalls quite easily, I chose the HTTP protocol.<\/p>\n<h3>Figuring out the HTTP request<\/h3>\n<p>The first step to writing the logic was simple - to see how browsers form a HTTP post request. With that, I started by constructing the following html form:<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;html&gt;\r\n&lt;body&gt;\r\n&lt;form action=&quot;http:\/\/ipv4.fiddler\/test\/GetPostRequest.php&quot;\r\nmethod=&quot;post&quot;\r\nenctype=&quot;multipart\/form-data&quot;&gt;\r\n&lt;p&gt;\r\n&lt;strong&gt;My file description:&lt;\/strong&gt;\r\n&lt;textarea name=&quot;myFileDescription&quot; rows=&quot;2&quot; cols=&quot;20&quot;&gt;\r\n&lt;\/textarea&gt;&lt;br\/&gt; &lt;br\/&gt;\r\n&lt;strong&gt;My file:&lt;\/strong&gt;&lt;br\/&gt;\r\n&lt;input type=&quot;file&quot; name=&quot;myFile&quot;&gt;\r\n&lt;\/p&gt;\r\n&lt;input type=&quot;submit&quot; value = &quot;Submit&quot;&gt;\r\n&lt;\/form&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<p>And using <a href=\"http:\/\/www.fiddler2.com\/fiddler2\/\" target=\"_blank\">Fiddler<\/a>, I was able to get the following HTTP post request that was sent by my browser to my <a href=\"http:\/\/www.techcoil.com\/blog\/how-to-receive-http-post-data-and-a-file-from-a-c-program-using-php\/\" title=\"How to receive HTTP post data and a file from a C# program using PHP\" target=\"_blank\">php script<\/a>, after I submitted a form input.<\/p>\n<pre>\r\n<code>POST http:\/\/127.0.0.1\/GetPostRequest.php \r\nHTTP\/1.1 Host: 127.0.0.1 \r\nConnection: keep-alive \r\nReferer: http:\/\/localhost\/GetPostRequest.php \r\nContent-Length: 1611568 \r\nCache-Control: max-age=0 \r\nOrigin: http:\/\/localhost \r\nUser-Agent: Mozilla\/5.0 (Windows NT 6.1; WOW64) AppleWebKit\/534.30 (KHTML, like Gecko) Chrome\/12.0.742.91 Safari\/534.30 \r\nContent-Type: multipart\/form-data; boundary=----WebKitFormBoundaryX6nBO7q27yQ1JNbb \r\nAccept: text\/html,application\/xhtml+xml,application\/xml;q=0.9,*\/*;q=0.8 \r\nAccept-Encoding: gzip,deflate,sdch \r\nAccept-Language: en-US,en;q=0.8 \r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 \r\n------WebKitFormBoundaryX6nBO7q27yQ1JNbb \r\nContent-Disposition: form-data; name=\"myFileDescription\" \r\n\r\nMy sample file description. \r\n------WebKitFormBoundaryX6nBO7q27yQ1JNbb \r\nContent-Disposition: form-data; name=\"myFile\"; filename=\"SomeRandomFile.pdf\" \r\nContent-Type: application\/pdf \r\n\r\nfile contents... \r\n\r\n------WebKitFormBoundaryX6nBO7q27yQ1JNbb--\r\n<\/code>\r\n<\/pre>\n<h3>Constructing the HTTP post request in C#<\/h3>\n<p>With the HTTP request constructed by my browser, constructing the HTTP post request in C# became very straightforward. There are classes from the System.Net and System.IO libraries that can be used for the generating and sending the request over to the server endpoint. The following is a proof of concept that I did for my actual solution:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n\r\n\/\/ Create a http request to the server endpoint that will pick up the\r\n\/\/ file and file description.\r\nHttpWebRequest requestToServerEndpoint =\r\n(HttpWebRequest)WebRequest.Create(&quot;http:\/\/localhost\/GetPostRequest.php&quot;);\r\n\r\nstring boundaryString = &quot;----SomeRandomText&quot;;\r\nstring fileUrl = @&quot;C:\\SomeRandomFile.pdf&quot;;\r\n\r\n\/\/ Set the http request header \\\\\r\nrequestToServerEndpoint.Method = WebRequestMethods.Http.Post;\r\nrequestToServerEndpoint.ContentType = &quot;multipart\/form-data; boundary=&quot; + boundaryString;\r\nrequestToServerEndpoint.KeepAlive = true;\r\nrequestToServerEndpoint.Credentials = System.Net.CredentialCache.DefaultCredentials;\r\n\r\n\/\/ Use a MemoryStream to form the post data request,\r\n\/\/ so that we can get the content-length attribute.\r\nMemoryStream postDataStream = new MemoryStream();\r\nStreamWriter postDataWriter = new StreamWriter(postDataStream);\r\n\r\n\/\/ Include value from the myFileDescription text area in the post data\r\npostDataWriter.Write(&quot;\\r\\n--&quot; + boundaryString + &quot;\\r\\n&quot;);\r\npostDataWriter.Write(&quot;Content-Disposition: form-data; name=\\&quot;{0}\\&quot;\\r\\n\\r\\n{1}&quot;,\r\n&quot;myFileDescription&quot;,\r\n&quot;A sample file description&quot;);\r\n\r\n\/\/ Include the file in the post data\r\npostDataWriter.Write(&quot;\\r\\n--&quot; + boundaryString + &quot;\\r\\n&quot;);\r\npostDataWriter.Write(&quot;Content-Disposition: form-data;&quot;\r\n+ &quot;name=\\&quot;{0}\\&quot;;&quot;\r\n+ &quot;filename=\\&quot;{1}\\&quot;&quot;\r\n+ &quot;\\r\\nContent-Type: {2}\\r\\n\\r\\n&quot;,\r\n&quot;myFile&quot;,\r\nPath.GetFileName(fileUrl),\r\nPath.GetExtension(fileUrl));\r\npostDataWriter.Flush();\r\n\r\n\/\/ Read the file\r\nFileStream fileStream = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);\r\nbyte&#x5B;] buffer = new byte&#x5B;1024];\r\nint bytesRead = 0;\r\nwhile ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)\r\n{\r\n    postDataStream.Write(buffer, 0, bytesRead);\r\n}\r\nfileStream.Close();\r\n\r\npostDataWriter.Write(&quot;\\r\\n--&quot; + boundaryString + &quot;--\\r\\n&quot;);\r\npostDataWriter.Flush();\r\n\r\n\/\/ Set the http request body content length\r\nrequestToServerEndpoint.ContentLength = postDataStream.Length;\r\n\r\n\/\/ Dump the post data from the memory stream to the request stream\r\nusing (Stream s = requestToServerEndpoint.GetRequestStream())\r\n{\r\n    postDataStream.WriteTo(s);\r\n}\r\npostDataStream.Close();\r\n\r\n<\/pre>\n<h2>Getting the response from the server<\/h2>\n<p>We get the server response by reading from the <a title=\"MSDN reference to System.Net.WebResponse class\" href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.net.webresponse.aspx\" target=\"_blank\">System.Net.WebResponse<\/a> instance, that can be retrieved via the <a title=\"MSDN reference to HttpWebRequest.GetResponseStream()\" href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.net.httpwebrequest.getresponse.aspx\" target=\"_blank\">HttpWebRequest.GetResponseStream()<\/a> method.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n\/\/ Grab the response from the server. WebException will be thrown\r\n\/\/ when a HTTP OK status is not returned\r\nWebResponse response = requestToServerEndpoint.GetResponse();\r\nStreamReader responseReader = new StreamReader(response.GetResponseStream());\r\nstring replyFromServer = responseReader.ReadToEnd();\r\n<\/pre>\n<h3>Related posts<\/h3>\n<ul>\n<li><a href=\"\/blog\/downloading-a-file-from-via-http-post-and-http-get-in-c\/\" target=\"_blank\">Downloading a file via HTTP post and HTTP get in C#<\/a><\/li>\n<li><a href=\"\/blog\/handling-web-server-communication-feedback-with-system-net-webexception\/\" target=\"_blank\">Handling web server communication feedback with System.Net.WebException in C#<\/a><\/li>\n<li><a href=\"\/blog\/uploading-large-http-multipart-request-with-system-net-httpwebrequest-in-c\/\" target=\"_blank\">Uploading large HTTP multipart request with System.Net.HttpWebRequest in C#<\/a><\/li>\n<li><a href=\"\/blog\/how-to-build-a-web-based-user-interaction-layer-in-c\/\" target=\"_blank\">How to build a web based user interaction layer in C#<\/a><\/li>\n<\/ul>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-1J\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-1J&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-1J&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F107&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>A few weeks back, I wrote some logic to send a file and a from a windows client over to a Java server endpoint. There are a few ways to do that: via application protocols like FTP and <a href=\"https:\/\/www.techcoil.com\/glossary\/http\/\" rel=\"noopener\" target=\"_blank\">HTTP<\/a> or even implementing a custom protocol using TCP\/IP. Since the Java server was already <a title=\"A mechanism for serving HTTP requests in C#\" href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/a-mechanism-for-serving-http-requests-in-c\/\" target=\"_blank\">serving HTTP requests<\/a> and that <a href=\"https:\/\/www.techcoil.com\/glossary\/http-request\/\" rel=\"noopener\" target=\"_blank\">HTTP requests<\/a> can usually get through firewalls quite easily, I chose the HTTP protocol.<\/p>\n","protected":false},"author":1,"featured_media":1189,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[20,23,137],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/C-Sharp-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-1J","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/107"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=107"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/107\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1189"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=107"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=107"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=107"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}