Saturday, January 11, 2014

Reading HTTP Request & Saving the files

Reading HTTP Post Request & Saving the files

Below is the way to actual & I would say standard & best way to read received HTTP Request If there are any files received through HTTP Post Sent then also you can save it & then write a response to the requested client...

         HttpRequest request = Context.Request;
           HttpResponse response = Context.Response;
           StreamReader readerReq = new StreamReader(request.InputStream);
           string req = readerReq.ReadToEnd();

           string IfAnyQueryString = Request.QueryString["IfAnyQueryString "].ToString();
           HttpFileCollection uploadFile = Request.Files;
           if (uploadFile.Count > 0)
           {
             //Follow this way to wile saving files
               for(int i =0; i<=uploadFile.count();i++)
               {
                 HttpPostedFile postedfile = uploadFile[i];
                 Stream filestream = postedfile.InputStream;
                 byte[] file = new byte[postedfile.ContentLength];
                 filestream.Read(file, 0, postedfile.ContentLength);
                 postedfile.SaveAs(@"DriveName:\\YourPath" + "\\" + postedfile.FileName);
              } 
           }
           else
           {
               using (var outfile = new StreamWriter(@"YourPath " + "\\" + "Request.txt"))
               {
                   outfile.Write(req);
               }
           }
      response.Output.Write("Sucess"); //Write response message if any

Note: This above code is used can also be used for internal testing of the previous post, before posting to remote url.




No comments: