By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,967 Members | 1,625 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,967 IT Pros & Developers. It's quick & easy.

HttpWebrequest Upload Of (image) Binary file.

P: n/a
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(byte Array));
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().GetResponseStre am());
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

Jun 15 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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 <gert.conra...@gmail.comwrote:
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(byte Array));
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().GetResponseStre am());
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

Jun 18 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.