Question : Post image file [Binary Data] using HttpWebRequest fails.

I am facing problem in posting image files as binary data to a webpage.

If I post the Form data using the Form tag Action=URL and Method="Post" , I m getting the required success result.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="http://www.babypredictor.com.au/gateway/api.php" runat="server" >
   image1Data Celeb ID: <asp:TextBox ID="image1DataID" text="808" runat="server"/><br />
image1Data JPEG:   <asp:FileUpload ID="image1Data" runat="server" />      <br />
image2Data Celeb ID: <asp:TextBox ID="image2DataID" text="809" runat="server"/><br /> OR
image2Data JPEG: <asp:FileUpload ID="image2Data" runat="server" /><br />
transaction_id : <asp:TextBox ID="transaction_id"  runat="server" Text="91193"/><br />
security : <asp:TextBox ID="security" runat="server" Text ="c1b840b731e84abd3f2d7639cd691389"/><br />
misc1 : <asp:TextBox  ID="misc1" text="miscval1" runat="server"/><br />
misc2 : <asp:TextBox  ID="misc2" text="miscval2" runat="server"/><br />
misc3 : <asp:TextBox  ID="misc3" text="miscval3" runat="server"/><br />
misc4 : <asp:TextBox  ID="misc4" text="miscval4" runat="server"/><br />
        <br />
        <asp:Button ID="Submit" runat="server" Text="Submit" />                          
    </form>
</body>
</html>

But , if I try to send the image data using the "HTTPWebRequest" by forming the headers , data and trailers , I m able to get the response from the posted URL , but the images are not morphed . [The target URL "http://www.babypredictor.com.au/gateway/api.php" receives 1 or 2 images we post and morph them into a single pic and send the success URL] .

Looks I m doing some mistake in the HTTP message forming while posting to the target URL . Can anyone please help me to figure the issue and get it work like the normal Form Post .

Attached is my solution. You can open using VS 2008.

I tried using Firebug to debug the post HTTP raw data and it looks almost same for both FORM posting and HTTPWebRequest Posting , but the images are not morphed for my later. Wish someone can find the issue and help me.

Here is my HTTPWebRequest Post Code Snippet.

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  public void HttpUploadFile(string url, HttpPostedFile file1, HttpPostedFile file2, string paramName, string contentType, NameValueCollection nvc)    
        //public void HttpUploadFile(string url, string file1, string file2, string paramName, string contentType, NameValueCollection nvc)
        {        
            //log.Debug(string.Format("Uploading {0} to {1}", file, url));
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;            
            wr.Referer = url;

            wr.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            wr.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;Q312461; .NET CLR 1.0.3705)";
            //wr.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,application/vnd.ms-excel, application/msword, application/x-shockwave-flash,*/*";

            Stream rs = wr.GetRequestStream();

            string formitem, header;

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in nvc.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.ASCII.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }

            rs.Write(boundarybytes, 0, boundarybytes.Length);
         
            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            header = string.Format(headerTemplate, paramName, file1, contentType);
            byte[] headerbytes = System.Text.Encoding.ASCII.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            Stream file1Stream = file1.InputStream;
            //FileStream fileStream = new FileStream(file1.FileName, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = file1Stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                byte[] encodedbuffer = System.Text.Encoding.ASCII.GetBytes(System.Text.ASCIIEncoding.ASCII.GetString(buffer));
                rs.Write(encodedbuffer, 0, bytesRead);
            }
           
            //fileStream.Close();

            if (file2.FileName!=string.Empty)
            {
                header = string.Format(headerTemplate, paramName, file2, contentType);
                headerbytes = System.Text.Encoding.ASCII.GetBytes(header);
                rs.Write(headerbytes, 0, headerbytes.Length);

                //fileStream = new FileStream(file2.FileName, FileMode.Open, FileAccess.Read);
                Stream file2Stream = file2.InputStream;
                bytesRead = 0;
                while ((bytesRead = file2Stream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    byte[] encodedbuffer = System.Text.Encoding.ASCII.GetBytes(System.Text.ASCIIEncoding.ASCII.GetString(buffer));
                    rs.Write(buffer, 0, bytesRead);
                }
                //fileStream.Close();
            }

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                //log.Debug(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));

                string response = reader2.ReadToEnd();

                if (response.ToLower().Contains("success"))
                {
                    string ResponseURL = response.Substring(response.IndexOf("success:") + "success:".Length);

                    Result.Text = response + "<br/><br/><br/>" + "<Img src='" + ResponseURL + "'>";
                }
                else
                    Result.Text = response + "<br/>";
            }
            catch (Exception ex)
            {
                //log.Error("Error uploading file", ex);
           
            }
            finally
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
                wr = null;
            }
        }

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

-Pamboo
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

using System.IO;
using System.Net;
using System.Text;
using System.Collections;
using System.Collections.Specialized;

using System.Security.Cryptography;
using System.Configuration;

namespace YuuBabies
{

    public partial class _Default : System.Web.UI.Page
    {   
        private string secrect_code;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                secrect_code = ConfigurationManager.AppSettings["Secret_code"];
                Random random = new Random();
                int randomNo = random.Next(99999);

                transaction_id.Text = (randomNo < 1000) ? (1000 + randomNo).ToString() : randomNo.ToString();
                security.Text = GetMD5Hash("yuz00b3byP" + transaction_id.Text);

            }
        }

        public string GetMD5Hash(string originalString)
        {
            byte[] textBytes = System.Text.Encoding.Default.GetBytes(originalString);
            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
                cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] hash = cryptHandler.ComputeHash(textBytes);
                string ret = "";
                foreach (byte a in hash)
                {
                    if (a < 16)
                        ret += "0" + a.ToString("x");
                    else
                        ret += a.ToString("x");
                }
                return ret;
            }
            catch
            {
                throw;
            }

        }

        protected void Submit_Click(object sender, EventArgs e)
        {
            HttpPostedFile file1 = image1Data.PostedFile;
            HttpPostedFile file2 = image2Data.PostedFile;

            if (file1.FileName!=string.Empty)
            {
                NameValueCollection nvc = new NameValueCollection();
                nvc.Add("image1DataID", image1DataID.Text);
                nvc.Add("image2DataID", image2DataID.Text);
                nvc.Add("transaction_id", transaction_id.Text);
                nvc.Add("security", security.Text);
                nvc.Add("misc1", misc1.Text);
                nvc.Add("misc2", misc2.Text);
                nvc.Add("misc3", misc3.Text);
                nvc.Add("misc4", misc4.Text);
                     
                //HttpUploadFile("http://www.babypredictor.com.au/gateway/api.php", imagefile1FullPathName.Value, imagefile2FullPathName.Value, "file", "image/jpeg", nvc);
                HttpUploadFile("http://www.babypredictor.com.au/gateway/api.php", file1,file2,"file", "image/jpeg", nvc);

            }

        }
        public void HttpUploadFile(string url, HttpPostedFile file1, HttpPostedFile file2, string paramName, string contentType, NameValueCollection nvc)     
        //public void HttpUploadFile(string url, string file1, string file2, string paramName, string contentType, NameValueCollection nvc)
        {         
            //log.Debug(string.Format("Uploading {0} to {1}", file, url));
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;            
            wr.Referer = url;

            wr.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            wr.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;Q312461; .NET CLR 1.0.3705)";
            //wr.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,application/vnd.ms-excel, application/msword, application/x-shockwave-flash,*/*";

            Stream rs = wr.GetRequestStream();

            string formitem, header;

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in nvc.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.ASCII.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }

            rs.Write(boundarybytes, 0, boundarybytes.Length);
          
            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            header = string.Format(headerTemplate, paramName, file1, contentType);
            byte[] headerbytes = System.Text.Encoding.ASCII.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            Stream file1Stream = file1.InputStream;
            //FileStream fileStream = new FileStream(file1.FileName, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = file1Stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                byte[] encodedbuffer = System.Text.Encoding.ASCII.GetBytes(System.Text.ASCIIEncoding.ASCII.GetString(buffer));
                rs.Write(encodedbuffer, 0, bytesRead);
            }
            
            //fileStream.Close();

            if (file2.FileName!=string.Empty)
            {
                header = string.Format(headerTemplate, paramName, file2, contentType);
                headerbytes = System.Text.Encoding.ASCII.GetBytes(header);
                rs.Write(headerbytes, 0, headerbytes.Length);

                //fileStream = new FileStream(file2.FileName, FileMode.Open, FileAccess.Read);
                Stream file2Stream = file2.InputStream;
                bytesRead = 0;
                while ((bytesRead = file2Stream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    byte[] encodedbuffer = System.Text.Encoding.ASCII.GetBytes(System.Text.ASCIIEncoding.ASCII.GetString(buffer));
                    rs.Write(buffer, 0, bytesRead);
                }
                //fileStream.Close();
            }

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                //log.Debug(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));

                string response = reader2.ReadToEnd();

                if (response.ToLower().Contains("success"))
                {
                    string ResponseURL = response.Substring(response.IndexOf("success:") + "success:".Length);

                    Result.Text = response + "<br/><br/><br/>" + "<Img src='" + ResponseURL + "'>";
                }
                else
                    Result.Text = response + "<br/>";
            }
            catch (Exception ex)
            {
                //log.Error("Error uploading file", ex);
           
            }
            finally
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
                wr = null;
            }
        }

    }
}

Answer : Post image file [Binary Data] using HttpWebRequest fails.

It takes some time to review your code, so in the mean time I'd spare time to evaluate your code to assist you, why not try something out-of-box which can serve your immediate need. Please have a look at the following URL and download the atta

http://aspnetupload.com/Upload-File-POST-HttpWebRequest-WebClient-RFC-1867.aspx

and download the code mentioned in the article from here: http://aspnetupload.com/Download-Source.aspx

Random Solutions  
 
programming4us programming4us