HttpWebrequest Upload Of (image) Binary file.

G

Gert Conradie

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
 
G

Gert

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.

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top