how to upload file via c# code

J

John Lee

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
 
J

John Lee

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
 
S

Steven Cheng[MSFT]

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.Length);
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);

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

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

FileStream fileStream = new FileStream(files, 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.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.)
 
J

John Lee

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 said:
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.Length);
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);

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

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

FileStream fileStream = new FileStream(files, 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.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.)
 
S

Steven Cheng[MSFT]

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.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);

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

memStream.Write(headerbytes,0,headerbytes.Length);


FileStream fileStream = new FileStream(files, 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.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;

}
============================
 
Joined
Aug 10, 2012
Messages
1
Reaction score
0
> 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!");
>
> }
>
> }

>[/color]

Hi.
Can you tell me that what is the variable "Path" in the code above?
 

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

Similar Threads


Top