473,651 Members | 3,004 Online
Bytes | Software Development & Data Engineering Community
+ 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="multip art/form-data"
action="process upload.aspx">
<input type=checkbox name="chkOverri de" 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
programmaticall y upload a file along with sending the checkbox to that
upload page?

Thanks very much!
John
Nov 17 '05 #1
5 103566
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.m icrosoft.com> wrote in message
news:a6******** ********@TK2MSF TNGXA02.phx.gbl ...
Hi John,

Welcome to MSDN newsgroup.
As for the uploading file programmaticall y 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(objec t sender, System.EventArg s e)
{

foreach(string key in Request.Files.K eys)
{
HttpPostedFile file = Request.Files.G et(key);
string fn = Path.GetFileNam eWithoutExtensi on(file.FileNam e) +
DateTime.Now.Mi llisecond + Path.GetExtensi on(file.FileNam e);

file.SaveAs(Ser ver.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 programmaticall y 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\\tes t.jpg";
WebClient wc = new WebClient();
wc.UploadFile(u rl,"post",file) ;

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

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

httpWebRequest2 .Credentials =
System.Net.Cred entialCache.Def aultCredentials ;

Stream memStream = new System.IO.Memor yStream();

byte[] boundarybytes = System.Text.Enc oding.ASCII.Get Bytes("\r\n--" +
boundary + "\r\n");
memStream.Write (boundarybytes, 0,boundarybytes .Length);
length += boundarybytes.L ength;

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.Len gth;i++)
{

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

byte[] headerbytes = System.Text.Enc oding.UTF8.GetB ytes(header);

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

FileStream fileStream = new FileStream(file s[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 .Length);
length += boundarybytes.L ength;

fileStream.Clos e();
}

httpWebRequest2 .ContentLength = memStream.Lengt h;

Stream requestStream = httpWebRequest2 .GetRequestStre am();

memStream.Posit ion = 0;
byte[] tempBuffer = new byte[memStream.Lengt h];
memStream.Read( tempBuffer,0,te mpBuffer.Length );
memStream.Close ();
requestStream.W rite(tempBuffer ,0,tempBuffer.L ength);
requestStream.C lose();
WebResponse webResponse2 = httpWebRequest2 .GetResponse();

Stream stream2 = webResponse2.Ge tResponseStream ();
StreamReader reader2 = new StreamReader(st ream2);
MessageBox.Show (reader2.ReadTo End());

webResponse2.Cl ose();
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.m icrosoft.com> wrote in message
news:yY******** ******@TK2MSFTN GXA02.phx.gbl.. .
Thanks for your reply John,

As for how to programmaticall y 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\\tes t.jpg";
WebClient wc = new WebClient();
wc.UploadFile(u rl,"post",file) ;

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

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

httpWebRequest2 .Credentials =
System.Net.Cred entialCache.Def aultCredentials ;

Stream memStream = new System.IO.Memor yStream();

byte[] boundarybytes = System.Text.Enc oding.ASCII.Get Bytes("\r\n--" +
boundary + "\r\n");
memStream.Write (boundarybytes, 0,boundarybytes .Length);
length += boundarybytes.L ength;

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.Len gth;i++)
{

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

byte[] headerbytes = System.Text.Enc oding.UTF8.GetB ytes(header);

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

FileStream fileStream = new FileStream(file s[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 .Length);
length += boundarybytes.L ength;

fileStream.Clos e();
}

httpWebRequest2 .ContentLength = memStream.Lengt h;

Stream requestStream = httpWebRequest2 .GetRequestStre am();

memStream.Posit ion = 0;
byte[] tempBuffer = new byte[memStream.Lengt h];
memStream.Read( tempBuffer,0,te mpBuffer.Length );
memStream.Close ();
requestStream.W rite(tempBuffer ,0,tempBuffer.L ength);
requestStream.C lose();
WebResponse webResponse2 = httpWebRequest2 .GetResponse();

Stream stream2 = webResponse2.Ge tResponseStream ();
StreamReader reader2 = new StreamReader(st ream2);
MessageBox.Show (reader2.ReadTo End());

webResponse2.Cl ose();
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 "UploadFilesToR emoteUrl" method which contains
an additioal NameValueCollec tion 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 UploadFilesToRe moteUrl(string url, string[] files, string
logpath, NameValueCollec tion nvc)
{

long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ti cks.ToString("x ");
HttpWebRequest httpWebRequest2 = (HttpWebRequest )WebRequest.Cre ate(url);
httpWebRequest2 .ContentType = "multipart/form-data; boundary=" +
boundary;
httpWebRequest2 .Method = "POST";
httpWebRequest2 .KeepAlive = true;
httpWebRequest2 .Credentials =
System.Net.Cred entialCache.Def aultCredentials ;

Stream memStream = new System.IO.Memor yStream();

byte[] boundarybytes = System.Text.Enc oding.ASCII.Get Bytes("\r\n--" +
boundary + "\r\n");
string formdataTemplat e = "\r\n--" + boundary +
"\r\nConten t-Disposition: form-data; name=\"{0}\";\r \n\r\n{1}";

foreach(string key in nvc.Keys)
{
string formitem = string.Format(f ormdataTemplate , key, nvc[key]);
byte[] formitembytes = System.Text.Enc oding.UTF8.GetB ytes(formitem);
memStream.Write (formitembytes, 0, formitembytes.L ength);
}
memStream.Write (boundarybytes, 0,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.Len gth;i++)
{

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

byte[] headerbytes = System.Text.Enc oding.UTF8.GetB ytes(header);

memStream.Write (headerbytes,0, headerbytes.Len gth);
FileStream fileStream = new FileStream(file s[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 .Length);
fileStream.Clos e();
}

httpWebRequest2 .ContentLength = memStream.Lengt h;

Stream requestStream = httpWebRequest2 .GetRequestStre am();

memStream.Posit ion = 0;
byte[] tempBuffer = new byte[memStream.Lengt h];
memStream.Read( tempBuffer,0,te mpBuffer.Length );
memStream.Close ();
requestStream.W rite(tempBuffer ,0,tempBuffer.L ength);
requestStream.C lose();
WebResponse webResponse2 = httpWebRequest2 .GetResponse();

Stream stream2 = webResponse2.Ge tResponseStream ();
StreamReader reader2 = new StreamReader(st ream2);
MessageBox.Show (reader2.ReadTo End());

webResponse2.Cl ose();
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 "UploadFilesToR emoteUrl" method which contains
an additioal NameValueCollec tion 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 UploadFilesToRe moteUrl(string url, string[] files, string
logpath, NameValueCollec tion nvc)
{

long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ti cks.ToString("x ");
HttpWebRequest httpWebRequest2 = (HttpWebRequest )WebRequest.Cre ate(url);
httpWebRequest2 .ContentType = "multipart/form-data; boundary=" +
boundary;
httpWebRequest2 .Method = "POST";
httpWebRequest2 .KeepAlive = true;
httpWebRequest2 .Credentials =
System.Net.Cred entialCache.Def aultCredentials ;

Stream memStream = new System.IO.Memor yStream();

byte[] boundarybytes = System.Text.Enc oding.ASCII.Get Bytes("\r\n--" +
boundary + "\r\n");
string formdataTemplat e = "\r\n--" + boundary +
"\r\nConten t-Disposition: form-data; name=\"{0}\";\r \n\r\n{1}";

foreach(string key in nvc.Keys)
{
string formitem = string.Format(f ormdataTemplate , key, nvc[key]);
byte[] formitembytes = System.Text.Enc oding.UTF8.GetB ytes(formitem);
memStream.Write (formitembytes, 0, formitembytes.L ength);
}
memStream.Write (boundarybytes, 0,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.Len gth;i++)
{

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

byte[] headerbytes = System.Text.Enc oding.UTF8.GetB ytes(header);

memStream.Write (headerbytes,0, headerbytes.Len gth);
FileStream fileStream = new FileStream(file s[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 .Length);
fileStream.Clos e();
}

httpWebRequest2 .ContentLength = memStream.Lengt h;

Stream requestStream = httpWebRequest2 .GetRequestStre am();

memStream.Posit ion = 0;
byte[] tempBuffer = new byte[memStream.Lengt h];
memStream.Read( tempBuffer,0,te mpBuffer.Length );
memStream.Close ();
requestStream.W rite(tempBuffer ,0,tempBuffer.L ength);
requestStream.C lose();
WebResponse webResponse2 = httpWebRequest2 .GetResponse();

Stream stream2 = webResponse2.Ge tResponseStream ();
StreamReader reader2 = new StreamReader(st ream2);
MessageBox.Show (reader2.ReadTo End());

webResponse2.Cl ose();
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
2868
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> <input type="hidden" name="MAX_FILE_SIZE" value="1000000"> <input type="file" name="img1" size="30"> </p> <p> <input type="submit" name="submit" value="Upload File">
5
5451
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.
3
2423
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 http post with a file upload. However, how do I upload file to the site using asp.net? thanks Brian
1
7256
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 filter (validate) when file is PDF or postscript.if you have code or you can tell me please help me. ps.i want to upload PDF and postscirpt file and when i upload file finish file will store at database i will download file return? thank you
4
11108
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 length is 129M or more for each file upload. I have 2 files upload at the same time. Therefore, I set the timeout is 20min and the size of file upload is 390MB (400,000 KBytes).
4
9168
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: http://www.motobit.com/tips/detpg_uploadvbaie/ It describes the vba code required to handle a very simple upload form:
1
8281
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, but outside.... Can anyone tell what i am doing wrong....?? And perhaps tell me what to do to put the file into the created directory...? Here is my code:
5
6803
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 inside html i am calling php file upload.php:- <?php
1
4396
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 attached a Log from HTTPAnalyzer. Anyhow, here's the code I'm running, Class File: HTMLElement.Upload = function(Params) { var FORM = new HTMLElement(HTMLElement.FORM,{
2
9424
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 result in different page on the right as someone clicks on SUBMIT with one's file attached. The uploaded file by clicking submit button should be PARSED on the right side of the page but when I click on the submit with the file now, it goes to the local...
0
8357
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
8277
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8700
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
8465
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
8581
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...
0
7298
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6158
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
5612
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
2701
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

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.