Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / ASP.NET / General / June 2007

Tip: Looking for answers? Try searching our database.

HttpWebrequest Upload Of (image) Binary file.

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Gert Conradie - 15 Jun 2007 14:39 GMT
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 - 18 Jun 2007 11:49 GMT
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

> The following code can uplaod text files. When i upload abinaryfile
> it fail.
[quoted text clipped - 168 lines]
>
> Thanks,gert

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.