473,493 Members | 2,229 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

how to upload file via c# code

Hi,

I have a simple web page that allow file to be uploaded, the upload page
looks like the following:

<form method="post" name="upload" enctype="multipart/form-data"
action="processupload.aspx">
<input type=checkbox name="chkOverride" value="1">
<input type=file name="filename">
<input type=submit value="Upload Data File" name="cmdSubmit">
</form>

My question is without using the web page, how could I use something in
System.Net such as HttpWebRequest or WebClient or some kind to
programmatically upload a file along with sending the checkbox to that
upload page?

Thanks very much!
John
Nov 17 '05 #1
5 103447
Hi, Steven,

I know how to write that code!!!
I am talking about how to write code to interact with that upload page
programatically - not on server side.

Thanks!
John
"Steven Cheng[MSFT]" <v-******@online.microsoft.com> wrote in message
news:a6****************@TK2MSFTNGXA02.phx.gbl...
Hi John,

Welcome to MSDN newsgroup.
As for the uploading file programmatically through Httpwebrequest or
webclient, I think both of them are OK. And webclient's uploaddata or
upload method is just using the httpwebrequest internally. Also, the
HttpWebRequest or webclient just send http post request to the target
document( page ). So your page's code logically is better to be something
like:

private void Page_Load(object sender, System.EventArgs e)
{

foreach(string key in Request.Files.Keys)
{
HttpPostedFile file = Request.Files.Get(key);
string fn = Path.GetFileNameWithoutExtension(file.FileName) +
DateTime.Now.Millisecond + Path.GetExtension(file.FileName);

file.SaveAs(Server.MapPath("./temp/" + fn));

Response.Write("<br>" + fn + " is uploaded!");

}

}

Then, our client side can use httpwebrequest/ webclient to post filestream
to that page. here are some tech article discussing on this:

http://www.c-sharpcorner.com/Code/20...DotNetBugs.asp

http://www.thecodeproject.com/csharp/UploadFileEx.asp

Also, I've attached a demo application which use HTTPWebRequest to upload
multi-files, you can also have a look if you have interesting ;-).

Hope helps.

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 17 '05 #2
Thanks for your reply John,

As for how to programmatically interact with the upload page in client .net
application, have you had a chance to see the code in the article I
provided or my attached demo? I'm sorry for my carelessness since I
assumed that you'll have a look at those article or my demo. Anyway, here
are some code snippet on using webclient or httpwebrequest to post file
stream:

#using WebClient
string url = "http://myserver/myapp/upload.aspx";
string file = "c:\\files\\test.jpg";
WebClient wc = new WebClient();
wc.UploadFile(url,"post",file);

#using httpWebrequest:
private void UploadFilesToRemoteUrl(string url, string[] files, string
logpath)
{

long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;

httpWebRequest2.Credentials =
System.Net.CredentialCache.DefaultCredentials;

Stream memStream = new System.IO.MemoryStream();

byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
boundary + "\r\n");
memStream.Write(boundarybytes,0,boundarybytes.Leng th);
length += boundarybytes.Length;

string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";
filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

for(int i=0;i<files.Length;i++)
{

string header = string.Format(headerTemplate,"file"+i,files[i]);

byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

memStream.Write(headerbytes,0,headerbytes.Length);
length += headerbytes.Length;

FileStream fileStream = new FileStream(files[i], FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];

int bytesRead = 0;

while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
{
memStream.Write(buffer, 0, bytesRead);
length += bytesRead;
}
memStream.Write(boundarybytes,0,boundarybytes.Leng th);
length += boundarybytes.Length;

fileStream.Close();
}

httpWebRequest2.ContentLength = memStream.Length;

Stream requestStream = httpWebRequest2.GetRequestStream();

memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer,0,tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer,0,tempBuffer.Length );
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();

Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
MessageBox.Show(reader2.ReadToEnd());

webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;

}
As we can see, weclient has encapsulated the underlying details of using
httpwebrequest to post data and the code will be very simple. However,
using httpwebrequest directly will give us more control over the posted
data stream as my above function inject multi file stream into the single
HttP request message.

Hope helps.

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
Nov 17 '05 #3
Thanks very much, Steven!!!

That's exactly what I am looking for - one more thing, the code snippet
shows how to upload the file only, I need to know how to upload the file
PLUS post extra form field back, Could you please help me on that? Thanks a
lot!

Regards,
John

"Steven Cheng[MSFT]" <v-******@online.microsoft.com> wrote in message
news:yY**************@TK2MSFTNGXA02.phx.gbl...
Thanks for your reply John,

As for how to programmatically interact with the upload page in client
.net
application, have you had a chance to see the code in the article I
provided or my attached demo? I'm sorry for my carelessness since I
assumed that you'll have a look at those article or my demo. Anyway, here
are some code snippet on using webclient or httpwebrequest to post file
stream:

#using WebClient
string url = "http://myserver/myapp/upload.aspx";
string file = "c:\\files\\test.jpg";
WebClient wc = new WebClient();
wc.UploadFile(url,"post",file);

#using httpWebrequest:
private void UploadFilesToRemoteUrl(string url, string[] files, string
logpath)
{

long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;

httpWebRequest2.Credentials =
System.Net.CredentialCache.DefaultCredentials;

Stream memStream = new System.IO.MemoryStream();

byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
boundary + "\r\n");
memStream.Write(boundarybytes,0,boundarybytes.Leng th);
length += boundarybytes.Length;

string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";
filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

for(int i=0;i<files.Length;i++)
{

string header = string.Format(headerTemplate,"file"+i,files[i]);

byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

memStream.Write(headerbytes,0,headerbytes.Length);
length += headerbytes.Length;

FileStream fileStream = new FileStream(files[i], FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];

int bytesRead = 0;

while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
{
memStream.Write(buffer, 0, bytesRead);
length += bytesRead;
}
memStream.Write(boundarybytes,0,boundarybytes.Leng th);
length += boundarybytes.Length;

fileStream.Close();
}

httpWebRequest2.ContentLength = memStream.Length;

Stream requestStream = httpWebRequest2.GetRequestStream();

memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer,0,tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer,0,tempBuffer.Length );
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();

Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
MessageBox.Show(reader2.ReadToEnd());

webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;

}
As we can see, weclient has encapsulated the underlying details of using
httpwebrequest to post data and the code will be very simple. However,
using httpwebrequest directly will give us more control over the posted
data stream as my above function inject multi file stream into the single
HttP request message.

Hope helps.

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 17 '05 #4
Hi John,

Glad that it is of assistance. As for post extra form fields together with
filestream, we can just add some additional sections into the request's
stream. Here is the modified "UploadFilesToRemoteUrl" method which contains
an additioal NameValueCollection parameter to specify the form datas we
want to post.

Hope helps. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

====================================

private void UploadFilesToRemoteUrl(string url, string[] files, string
logpath, NameValueCollection nvc)
{

long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest2.ContentType = "multipart/form-data; boundary=" +
boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;
httpWebRequest2.Credentials =
System.Net.CredentialCache.DefaultCredentials;

Stream memStream = new System.IO.MemoryStream();

byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
boundary + "\r\n");
string formdataTemplate = "\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

foreach(string key in nvc.Keys)
{
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
}
memStream.Write(boundarybytes,0,boundarybytes.Leng th);

string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";
filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

for(int i=0;i<files.Length;i++)
{

string header = string.Format(headerTemplate,"file"+i,files[i]);

byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

memStream.Write(headerbytes,0,headerbytes.Length);
FileStream fileStream = new FileStream(files[i], FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];

int bytesRead = 0;

while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
{
memStream.Write(buffer, 0, bytesRead);

}
memStream.Write(boundarybytes,0,boundarybytes.Leng th);
fileStream.Close();
}

httpWebRequest2.ContentLength = memStream.Length;

Stream requestStream = httpWebRequest2.GetRequestStream();

memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer,0,tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer,0,tempBuffer.Length );
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();

Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
MessageBox.Show(reader2.ReadToEnd());

webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;

}
============================

Nov 17 '05 #5
Hi John,

Glad that it is of assistance. As for post extra form fields together with
filestream, we can just add some additional sections into the request's
stream. Here is the modified "UploadFilesToRemoteUrl" method which contains
an additioal NameValueCollection parameter to specify the form datas we
want to post.

Hope helps. Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

====================================

private void UploadFilesToRemoteUrl(string url, string[] files, string
logpath, NameValueCollection nvc)
{

long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest2.ContentType = "multipart/form-data; boundary=" +
boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;
httpWebRequest2.Credentials =
System.Net.CredentialCache.DefaultCredentials;

Stream memStream = new System.IO.MemoryStream();

byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
boundary + "\r\n");
string formdataTemplate = "\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

foreach(string key in nvc.Keys)
{
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
}
memStream.Write(boundarybytes,0,boundarybytes.Leng th);

string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";
filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

for(int i=0;i<files.Length;i++)
{

string header = string.Format(headerTemplate,"file"+i,files[i]);

byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

memStream.Write(headerbytes,0,headerbytes.Length);
FileStream fileStream = new FileStream(files[i], FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];

int bytesRead = 0;

while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
{
memStream.Write(buffer, 0, bytesRead);

}
memStream.Write(boundarybytes,0,boundarybytes.Leng th);
fileStream.Close();
}

httpWebRequest2.ContentLength = memStream.Length;

Stream requestStream = httpWebRequest2.GetRequestStream();

memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer,0,tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer,0,tempBuffer.Length );
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();

Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
MessageBox.Show(reader2.ReadToEnd());

webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;

}
============================

Nov 17 '05 #6

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

Similar topics

1
2853
by: Muppy | last post by:
I've created a page with a form to upload files: <h1>Upload di un file</h1> <form enctype="multipart/form-data" method="post" action="do_upload1.php"> <p><strong>File da trasferire:</strong><br>...
5
5429
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. ...
3
2407
by: Brian | last post by:
Hi, I've been trying to find a way to upload file to another site that is not using IIS. The site that I want to upload file to has a simple php script to receive file uploaded through standard...
1
7244
by: akiko | last post by:
i am student and i must to do project about web app by Ruby on rails i can not do past upload file.i try looking code but i just meet upload file image. i want to code upload file that it must to...
4
11087
by: bienwell | last post by:
Hi all, I developed an web page in ASP.NET to upload file into the server. In the Web.config file, I declared <httpRuntime executionTimeout="1200" maxRequestLength="400000" /> The MAX...
4
9122
by: google.com | last post by:
Hi there! I've been digging around looking for a sample on how to upload a file without user action. I found the following article covering the area: ...
1
8265
by: printline | last post by:
Hello all I have a php script that uploads a file from a form into a directory. The directory is automatically created through the script. But the upload file is not put in to the directory,...
5
6787
by: kailashchandra | last post by:
I am trying to upload a file in php,but it gives me error msg please Help me? My Code is like below:- i have one php file named upload.php and i have another html file named upload.html and...
1
4385
Canabeez
by: Canabeez | last post by:
Hi all, anyone has an idea why IE is not uploading file and FF does? I'm creating a FORM + IFRAME using DOM and trying to upload a file, now Firefox and Chrome do thins perfectly. I have...
2
9395
by: lka527 | last post by:
I am trying to make a site available for someone to *upload* certain type of text file (.txt) that can be parsed by written code. the upload file is available on the main site but I need this to...
0
7119
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,...
1
6873
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...
0
7367
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...
0
5453
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4579
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...
0
3088
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1400
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 ...
1
644
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
285
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...

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.