473,805 Members | 2,278 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HttpWebrequest Upload Of (image) Binary file.

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.ReadLin e();
}
private static string GetMultipartBou ndary()
{
return String.Format(" *************** ********{0}",
DateTime.Now.Ti cks);
}
private static void UploadImageFile (string fileNameToUpLoa d)
{
Console.WriteLi ne("");

Console.WriteLi ne("=========== =============== ==============" );
Console.WriteLi ne("UploadImage File");

Console.WriteLi ne("=========== =============== ==============" );

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

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

url = "http://server/myreceivepage.a sp";
request =
(HttpWebRequest )System.Net.Web Request.Create( url);

boundry = GetMultipartBou ndary();
databoundary = "--" + boundry;
uploadFileFormC ontrolName = "fileinput1 ";
//I think here is my problem:
enc = Encoding.GetEnc oding(1252);
//enc = Encoding.ASCII;
//enc = Encoding.UTF8;
//enc = Encoding.Unicod e;
//enc = Encoding.BigEnd ianUnicode;
enc = Encoding.Defaul t;
//enc = Encoding.UTF32;
//enc = Encoding.UTF7;

fileToUpLoad = new FileInfo(fileNa meToUpLoad);
//this can be enhanced, ok for testing
switch (fileToUpLoad.E xtension)
{
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.Le ngth;
FileStream fStream = new FileStream(file NameToUpLoad,
FileMode.Open, FileAccess.Read );
BinaryReader br = new BinaryReader(fS tream, enc);
byteArray = br.ReadBytes((i nt)numBytes);
br.Close();
fStream.Close() ;

//request.Credent ials = new NetworkCredenti al("user",
"password") ;

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

reqString.Appen d(databoundary + "\r\n");
reqString.Appen d(string.Format ("Content-Disposition: form-
data; name=\"{0}\"; ", uploadFileFormC ontrolName));
reqString.Appen d(string.Format ("filename=\"{0 }\"\r\n",
fileToUpLoad.Na me));
reqString.Appen d(string.Format ("Content-Type: {0}\r\n",
filetype));
byteArrayBefore = enc.GetBytes(re qString.ToStrin g());

//normally file content goes here - currently in
byteArray[]
//Start to build request string END:
//=============== =============== ====
reqString = new StringBuilder() ;
reqString.Appen d("\r\n");
reqString.Appen dFormat("--{0}--\r\n", boundry);
byteArrayAfter = enc.GetBytes(re qString.ToStrin g());

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

request.Content Length = (int)oPostData. BaseStream.Leng th;
request.Content Length = byteArrayBefore .Length +
byteArray.Lengt h + byteArrayAfter. Length;

try
{
Stream stream = request.GetRequ estStream();
oPostStream.Wri teTo(stream);
StreamReader reader = new
StreamReader(re quest.GetRespon se().GetRespons eStream());
string myOrginalRawHtm l = reader.ReadToEn d();
myOrginalRawHtm l = myOrginalRawHtm l.Replace("<br> ", "\r
\n");
Console.WriteLi ne(myOrginalRaw Html);
}
catch (System.Excepti on ex)
{
Console.WriteLi ne(ex.Message);
}

Console.WriteLi ne("=========== =============== ==============" );
Console.WriteLi ne("");
}

Thanks, gert

Jun 15 '07 #1
1 4825
Found my mistake. (It even failed for txt files where it lost the frst
two characters.)

Change this:
reqString.Appen d(string.Format ("Content-Type: {0}\r\n", filetype));
To (Add extra line break):
reqString.Appen d(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.ReadLin e();
}

private static string GetMultipartBou ndary()
{
return String.Format(" *************** ********{0}",
DateTime.Now.Ti cks);
}
private static void UploadImageFile (string fileNameToUpLoa d)
{
Console.WriteLi ne("");

Console.WriteLi ne("=========== =============== ==============" );
Console.WriteLi ne("UploadImage File");

Console.WriteLi ne("=========== =============== ==============" );

string url;
string uploadFileFormC ontrolName;
string boundry;
string databoundary;
string filetype;
StringBuilder reqString;
Encoding enc;
MemoryStream oPostStream;
BinaryWriter oPostData;
HttpWebRequestr equest;
System.IO.FileI nfo fileToUpLoad;
byte[] byteArrayBefore ;
byte[] byteArray;
byte[] byteArrayAfter;

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

url = "http://server/myreceivepage.a sp";
request =
(HttpWebRequest )System.Net.Web Request.Create( url);

boundry = GetMultipartBou ndary();
databoundary = "--" + boundry;
uploadFileFormC ontrolName = "fileinput1 ";
//I think here is my problem:
enc = Encoding.GetEnc oding(1252);
//enc = Encoding.ASCII;
//enc = Encoding.UTF8;
//enc = Encoding.Unicod e;
//enc = Encoding.BigEnd ianUnicode;
enc = Encoding.Defaul t;
//enc = Encoding.UTF32;
//enc = Encoding.UTF7;

fileToUpLoad = new FileInfo(fileNa meToUpLoad);
//this can be enhanced, ok for testing
switch (fileToUpLoad.E xtension)
{
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.Le ngth;
FileStream fStream = new FileStream(file NameToUpLoad,
FileMode.Open, FileAccess.Read );
BinaryReader br = new BinaryReader(fS tream, enc);
byteArray = br.ReadBytes((i nt)numBytes);
br.Close();
fStream.Close() ;

//request.Credent ials = new NetworkCredenti al("user",
"password") ;

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

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

reqString.Appen d(databoundary + "\r\n");
reqString.Appen d(string.Format ("Content-Disposition: form-
data; name=\"{0}\"; ", uploadFileFormC ontrolName));
reqString.Appen d(string.Format ("filename=\"{0 }\"\r\n",
fileToUpLoad.Na me));
reqString.Appen d(string.Format ("Content-Type: {0}\r\n",
filetype));
byteArrayBefore = enc.GetBytes(re qString.ToStrin g());

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

//Start to build request string END:
//=============== =============== ====
reqString = new StringBuilder() ;
reqString.Appen d("\r\n");
reqString.Appen dFormat("--{0}--\r\n", boundry);
byteArrayAfter = enc.GetBytes(re qString.ToStrin g());

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

request.Content Length = (int)oPostData. BaseStream.Leng th;
request.Content Length = byteArrayBefore .Length +
byteArray.Lengt h + byteArrayAfter. Length;

try
{
Stream stream = request.GetRequ estStream();
oPostStream.Wri teTo(stream);
StreamReader reader = new
StreamReader(re quest.GetRespon se().GetRespons eStream());
string myOrginalRawHtm l = reader.ReadToEn d();
myOrginalRawHtm l = myOrginalRawHtm l.Replace("<br> ", "\r
\n");
Console.WriteLi ne(myOrginalRaw Html);
}
catch (System.Excepti on ex)
{
Console.WriteLi ne(ex.Message);
}

Console.WriteLi ne("=========== =============== ==============" );
Console.WriteLi ne("");
}

Thanks,gert

Jun 18 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
11769
by: dave | last post by:
Hello there, I am at my wit's end ! I have used the following script succesfully to upload an image to my web space. But what I really want to be able to do is to update an existing record in a table in MySQL with the path & filename to the image. I have successfully uploaded and performed an update query on the database, but the problem I have is I cannot retain the primary key field in a variable which is then used in a SQL update...
5
5470
by: Dave Smithz | last post by:
Hi There, I have a PHP script that sends an email with attachment and works great when provided the path to the file to send. However this file needs to be on the same server as the script. I want to develop a webpage where people can send attachments that are stored on their local PC.
0
2385
by: Paul Hamlington | last post by:
Hello, I've been programming in ASP for a little while now and quite an advanced user, but I have come across an unusual problem in which I need assistance. I have built my own image upload, I have two versions of the binary to string conversion one fast, one slow because some servers use chillisoft and therefore the append function in not accessible for a disconnected recordset.
8
12229
by: Du | last post by:
I'm trying to automate the upload process to yousendit.com, but the file size doesn't add up and yousendit.com keep rejecting my upload (it accepts the upload until the very end) I don't know what i'm missing, I use Fiddler and I got my header and body to a very close match, but the content-length is slightly off and I got no clue why Sorry for the lengthy post, but i have no other way of showing my work
9
3905
by: Steve Poe | last post by:
I work for an animal hospital trying to use PHP to store an animal's dental x-rays to a file server. I can browse for the xray on the local desktop computer then click "Upload Image". This works fine. The doctors want fewer steps to follow. So, it was asked if I can configure the browser to load/submit the image 'xray.tif' each time they click "Upload Image" instead of the doctor/animal technician having to look for for dental x-ray...
0
2836
by: dann2 | last post by:
hello, i try to upload in an access db two pictures at the same time. i use the adjusted sample code from persits. it looks like this: ... '<% ' Create an instance of AspUpload object 'Set Upload = Server.CreateObject("Persits.Upload") ' Capture uploaded file. Save returns the number of files uploaded 'Count = Upload.Save(Path) 'If Count = 0 Then 'Response.Write "message"
18
34858
jhardman
by: jhardman | last post by:
Have you ever wanted to upload files through a form and thought, "I'd really like to use ASP, it surely has that capability, but the tutorial I used to learn ASP didn't mention how to do this."? Have you looked around trying to find simple solutions but didn't want to wade through pages of complex code? Have you balked at paying for premade solutions that are probably overkill for your particular project? I'd like to walk you through the...
1
8049
by: Proogeren | last post by:
I have a problem with a httpwebrequest that I am creating. The request in itself looks correct but using fiddler I see that a www-authentication header is sent along as well. The code is pasted below. I do not add any www-authentication header here so I was wondering if anyone knows how to remove it. I have used almost 2 days trying to figure this out so help would be highly appreciated. CORRECT No proxy-authenticate header is present no...
5
8853
by: kamlesh20J | last post by:
Hello, I am trying to use HttpWebRequest to send some POST data I have accomplished this using: HttpWebRequest req = (HttpWebRequest) WebRequest.Create("http://mysite.com/index.php"); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; string postData = "login=value1&pwd=value2&file=filename" req.ContentLength = postData.Length;
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10369
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10109
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6876
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3847
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.