HttpWebrequest Upload Of (image) Binary file.

Discussion in 'ASP .Net' started by Gert Conradie, Jun 15, 2007.

  1. The following code can uplaod text files. When i upload a binary file
    it fail.

    I might be:
    1) using the wrong Encoding
    2) will have to System.Convert.ToBase64String the content of the
    binary file

    Any help / suggestions would be much appreciated. Already spend a lot
    of time on this.

    Regards, Gert

    Here is the console application code:

    static void Main(string[] args)
    {
    UploadImageFile(@"C:\imagetest.JPG"); //fail
    UploadImageFile(@"C:\test.txt"); //work
    Console.ReadLine();
    }


    private static string GetMultipartBoundary()
    {
    return String.Format("***********************{0}",
    DateTime.Now.Ticks);
    }
    private static void UploadImageFile(string fileNameToUpLoad)
    {
    Console.WriteLine("");

    Console.WriteLine("========================================");
    Console.WriteLine("UploadImageFile");

    Console.WriteLine("========================================");

    string url;
    string uploadFileFormControlName;
    string boundry;
    string databoundary;
    string filetype;
    StringBuilder reqString;
    Encoding enc;
    MemoryStream oPostStream;
    BinaryWriter oPostData;
    HttpWebRequest request;
    System.IO.FileInfo fileToUpLoad;
    byte[] byteArrayBefore;
    byte[] byteArray;
    byte[] byteArrayAfter;

    reqString = new StringBuilder();
    oPostStream = new MemoryStream();
    oPostData = new BinaryWriter(oPostStream);

    url = "http://server/myreceivepage.asp";
    request =
    (HttpWebRequest)System.Net.WebRequest.Create(url);

    boundry = GetMultipartBoundary();
    databoundary = "--" + boundry;
    uploadFileFormControlName = "fileinput1";
    //I think here is my problem:
    enc = Encoding.GetEncoding(1252);
    //enc = Encoding.ASCII;
    //enc = Encoding.UTF8;
    //enc = Encoding.Unicode;
    //enc = Encoding.BigEndianUnicode;
    enc = Encoding.Default;
    //enc = Encoding.UTF32;
    //enc = Encoding.UTF7;

    fileToUpLoad = new FileInfo(fileNameToUpLoad);
    //this can be enhanced, ok for testing
    switch (fileToUpLoad.Extension)
    {
    case ".txt":
    filetype = "text/plain";
    break;

    case ".jpg":
    filetype = "image/pjpeg";
    break;

    case ".gif":
    filetype = "image/gif";
    break;

    default:
    filetype = "text/plain";
    break;
    }

    //read the file content and store in byteArray[]
    long numBytes = fileToUpLoad.Length;
    FileStream fStream = new FileStream(fileNameToUpLoad,
    FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fStream, enc);
    byteArray = br.ReadBytes((int)numBytes);
    br.Close();
    fStream.Close();

    //request.Credentials = new NetworkCredential("user",
    "password");

    request.Method = "POST";
    request.ContentType = "multipart/form-data;boundary=" +
    boundry;


    //Start to build request string:
    //==================================
    //Should you have extra form inputs other than uploadfile
    control:
    //reqString.Append("--" + boundry + "\r\n");
    //reqString.Append(databoundary + "\r\n");
    //reqString.Append("Content-Disposition: form-data; name=
    \"txtAddPerson\";");
    //reqString.Append("\r\n");
    //reqString.Append("\r\n");
    //reqString.Append("myValue");
    //reqString.Append("\r\n");

    reqString.Append(databoundary + "\r\n");
    reqString.Append(string.Format("Content-Disposition: form-
    data; name=\"{0}\"; ", uploadFileFormControlName));
    reqString.Append(string.Format("filename=\"{0}\"\r\n",
    fileToUpLoad.Name));
    reqString.Append(string.Format("Content-Type: {0}\r\n",
    filetype));
    byteArrayBefore = enc.GetBytes(reqString.ToString());

    //normally file content goes here - currently in
    byteArray[]


    //Start to build request string END:
    //==================================
    reqString = new StringBuilder();
    reqString.Append("\r\n");
    reqString.AppendFormat("--{0}--\r\n", boundry);
    byteArrayAfter = enc.GetBytes(reqString.ToString());

    oPostData.Write(byteArrayBefore);
    oPostData.Write(byteArray);
    //maybe like this: ?
    //
    oPostData.Write(System.Convert.ToBase64String(byteArray));
    oPostData.Write(byteArrayAfter);

    request.ContentLength = (int)oPostData.BaseStream.Length;
    request.ContentLength = byteArrayBefore.Length +
    byteArray.Length + byteArrayAfter.Length;

    try
    {
    Stream stream = request.GetRequestStream();
    oPostStream.WriteTo(stream);
    StreamReader reader = new
    StreamReader(request.GetResponse().GetResponseStream());
    string myOrginalRawHtml = reader.ReadToEnd();
    myOrginalRawHtml = myOrginalRawHtml.Replace("<br>", "\r
    \n");
    Console.WriteLine(myOrginalRawHtml);
    }
    catch (System.Exception ex)
    {
    Console.WriteLine(ex.Message);
    }

    Console.WriteLine("========================================");
    Console.WriteLine("");
    }



    Thanks, gert
     
    Gert Conradie, Jun 15, 2007
    #1
    1. Advertising

  2. Gert Conradie

    Gert Guest

    Found my mistake. (It even failed for txt files where it lost the frst
    two characters.)

    Change this:
    reqString.Append(string.Format("Content-Type: {0}\r\n", filetype));
    To (Add extra line break):
    reqString.Append(string.Format("Content-Type: {0}\r\n\r\n",
    filetype));

    Regards, gert

    On Jun 15, 3:39 pm, Gert Conradie <> wrote:
    > The following code can uplaod text files. When i upload abinaryfile
    > it fail.
    >
    > I might be:
    > 1) using the wrong Encoding
    > 2) will have to System.Convert.ToBase64String the content of thebinaryfile
    >
    > Any help / suggestions would be much appreciated. Already spend a lot
    > of time on this.
    >
    > Regards,Gert
    >
    > Here is the console application code:
    >
    > static void Main(string[] args)
    > {
    > UploadImageFile(@"C:\imagetest.JPG"); //fail
    > UploadImageFile(@"C:\test.txt"); //work
    > Console.ReadLine();
    > }
    >
    > private static string GetMultipartBoundary()
    > {
    > return String.Format("***********************{0}",
    > DateTime.Now.Ticks);
    > }
    > private static void UploadImageFile(string fileNameToUpLoad)
    > {
    > Console.WriteLine("");
    >
    > Console.WriteLine("========================================");
    > Console.WriteLine("UploadImageFile");
    >
    > Console.WriteLine("========================================");
    >
    > string url;
    > string uploadFileFormControlName;
    > string boundry;
    > string databoundary;
    > string filetype;
    > StringBuilder reqString;
    > Encoding enc;
    > MemoryStream oPostStream;
    > BinaryWriter oPostData;
    > HttpWebRequestrequest;
    > System.IO.FileInfo fileToUpLoad;
    > byte[] byteArrayBefore;
    > byte[] byteArray;
    > byte[] byteArrayAfter;
    >
    > reqString = new StringBuilder();
    > oPostStream = new MemoryStream();
    > oPostData = new BinaryWriter(oPostStream);
    >
    > url = "http://server/myreceivepage.asp";
    > request =
    > (HttpWebRequest)System.Net.WebRequest.Create(url);
    >
    > boundry = GetMultipartBoundary();
    > databoundary = "--" + boundry;
    > uploadFileFormControlName = "fileinput1";
    > //I think here is my problem:
    > enc = Encoding.GetEncoding(1252);
    > //enc = Encoding.ASCII;
    > //enc = Encoding.UTF8;
    > //enc = Encoding.Unicode;
    > //enc = Encoding.BigEndianUnicode;
    > enc = Encoding.Default;
    > //enc = Encoding.UTF32;
    > //enc = Encoding.UTF7;
    >
    > fileToUpLoad = new FileInfo(fileNameToUpLoad);
    > //this can be enhanced, ok for testing
    > switch (fileToUpLoad.Extension)
    > {
    > case ".txt":
    > filetype = "text/plain";
    > break;
    >
    > case ".jpg":
    > filetype = "image/pjpeg";
    > break;
    >
    > case ".gif":
    > filetype = "image/gif";
    > break;
    >
    > default:
    > filetype = "text/plain";
    > break;
    > }
    >
    > //read the file content and store in byteArray[]
    > long numBytes = fileToUpLoad.Length;
    > FileStream fStream = new FileStream(fileNameToUpLoad,
    > FileMode.Open, FileAccess.Read);
    > BinaryReader br = new BinaryReader(fStream, enc);
    > byteArray = br.ReadBytes((int)numBytes);
    > br.Close();
    > fStream.Close();
    >
    > //request.Credentials = new NetworkCredential("user",
    > "password");
    >
    > request.Method = "POST";
    > request.ContentType = "multipart/form-data;boundary=" +
    > boundry;
    >
    > //Start to build request string:
    > //==================================
    > //Should you have extra form inputs other than uploadfile
    > control:
    > //reqString.Append("--" + boundry + "\r\n");
    > //reqString.Append(databoundary + "\r\n");
    > //reqString.Append("Content-Disposition: form-data; name=
    > \"txtAddPerson\";");
    > //reqString.Append("\r\n");
    > //reqString.Append("\r\n");
    > //reqString.Append("myValue");
    > //reqString.Append("\r\n");
    >
    > reqString.Append(databoundary + "\r\n");
    > reqString.Append(string.Format("Content-Disposition: form-
    > data; name=\"{0}\"; ", uploadFileFormControlName));
    > reqString.Append(string.Format("filename=\"{0}\"\r\n",
    > fileToUpLoad.Name));
    > reqString.Append(string.Format("Content-Type: {0}\r\n",
    > filetype));
    > byteArrayBefore = enc.GetBytes(reqString.ToString());
    >
    > //normally file content goes here - currently in
    > byteArray[]
    >
    > //Start to build request string END:
    > //==================================
    > reqString = new StringBuilder();
    > reqString.Append("\r\n");
    > reqString.AppendFormat("--{0}--\r\n", boundry);
    > byteArrayAfter = enc.GetBytes(reqString.ToString());
    >
    > oPostData.Write(byteArrayBefore);
    > oPostData.Write(byteArray);
    > //maybe like this: ?
    > //
    > oPostData.Write(System.Convert.ToBase64String(byteArray));
    > oPostData.Write(byteArrayAfter);
    >
    > request.ContentLength = (int)oPostData.BaseStream.Length;
    > request.ContentLength = byteArrayBefore.Length +
    > byteArray.Length + byteArrayAfter.Length;
    >
    > try
    > {
    > Stream stream = request.GetRequestStream();
    > oPostStream.WriteTo(stream);
    > StreamReader reader = new
    > StreamReader(request.GetResponse().GetResponseStream());
    > string myOrginalRawHtml = reader.ReadToEnd();
    > myOrginalRawHtml = myOrginalRawHtml.Replace("<br>", "\r
    > \n");
    > Console.WriteLine(myOrginalRawHtml);
    > }
    > catch (System.Exception ex)
    > {
    > Console.WriteLine(ex.Message);
    > }
    >
    > Console.WriteLine("========================================");
    > Console.WriteLine("");
    > }
    >
    > Thanks,gert
     
    Gert, Jun 18, 2007
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?U2FyYXY=?=

    Upload a file without file Upload control - ASP.Net

    =?Utf-8?B?U2FyYXY=?=, Aug 2, 2005, in forum: ASP .Net
    Replies:
    3
    Views:
    2,594
    Bruce Barker
    Aug 3, 2005
  2. Roland Riess
    Replies:
    0
    Views:
    2,883
    Roland Riess
    Mar 7, 2006
  3. Heather Fraser
    Replies:
    0
    Views:
    670
    Heather Fraser
    Jul 5, 2004
  4. =?Utf-8?B?am9l?=
    Replies:
    4
    Views:
    3,121
    =?Utf-8?B?am9l?=
    Jul 27, 2006
  5. Rob
    Replies:
    1
    Views:
    854
    bruce barker
    May 12, 2008
Loading...

Share This Page