views:

160

answers:

2

Hello All,

Here is my code to post the file. I use asp fileupload control to get the file stream.

HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://localhost:2518/Web/CrossPage.aspx");
requestToSender.Method = "POST";
requestToSender.ContentType = "multipart/form-data";
requestToSender.KeepAlive = true;
requestToSender.Credentials = System.Net.CredentialCache.DefaultCredentials;
requestToSender.ContentLength = BtnUpload.PostedFile.ContentLength;

BinaryReader binaryReader = new BinaryReader(BtnUpload.PostedFile.InputStream);
byte[] binData = binaryReader.ReadBytes(BtnUpload.PostedFile.ContentLength);


Stream requestStream = requestToSender.GetRequestStream();
requestStream.Write(binData, 0, binData.Length);
requestStream.Close();

HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse();
string fromSender = string.Empty;

using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream()))
 {
  fromSender = responseReader.ReadToEnd();
 }
XMLString.Text = fromSender;

In the page load of CrossPage.aspx i have the following code

 NameValueCollection postPageCollection = Request.Form;

 foreach (string name in postPageCollection.AllKeys)
  {
   Response.Write(name + " " + postPageCollection[name]);
  }

 HttpFileCollection postCollection = Request.Files;
 foreach (string name in postCollection.AllKeys)
 {
   HttpPostedFile aFile = postCollection[name];
   aFile.SaveAs(Server.MapPath(".") + "/" + Path.GetFileName(aFile.FileName));
 }
 string strxml = "sample";

 Response.Clear();
 Response.Write(strxml);

I don't get the file in Request.Files. The byte array is created. What was wrong with my HttpWebRequest?

+1  A: 

multipart/form-data doesn't consist of simply writing the file bytes to the request stream. You need to respect the RFC 1867. You may take a look at this post of how this could be done with multiple files.

Darin Dimitrov
I am really new to this. Can you please explain what was missing actually?
Sri Kumar
+1  A: 

I wrote an article on how to upload form data and files to a HTML FORM using multipart/form-data.

feroze