473,703 Members | 2,323 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 103604
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
2876
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
5464
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
2429
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
7261
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
11116
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
9181
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
8286
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
6809
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
4409
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
9433
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
9121
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
9017
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
8962
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
7867
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
6588
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
5922
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();...
0
4432
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2450
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.