Go C # use HttpWebRequest to upload files and show progress under WinForm

Source: Internet
Author: User

<summary>
Uploading local files to the specified server (HttpWebRequest method)
</summary>
<param name= "Address" > Files uploaded to the server </param>
<param name= "Filenamepath" > local file to upload (full path) </param>
<param name= "Savename" > file name after upload </param>
<param name= "ProgressBar" > Upload progress bar </param>
<returns> successfully returned 1, failed to return 0</returns>
private int Upload_request (string address, String Filenamepath, String savename, ProgressBar ProgressBar)
{
int returnvalue = 0; The file to upload
FileStream fs = new FileStream (Filenamepath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader (FS); Time stamp
String strboundary = "----------" + DateTime.Now.Ticks.ToString ("x");
byte[] Boundarybytes = Encoding.ASCII.GetBytes ("\r\n--" + strboundary + "\ r \ n"); Request header Information
StringBuilder sb = new StringBuilder ();
Sb. Append ("--");
Sb. Append (strboundary);
Sb. Append ("\ r \ n");
Sb. Append ("Content-disposition:form-data; Name=\ "");
Sb. Append ("file");
Sb. Append ("\"; filename=\ "");
Sb. Append (Savename);
Sb. Append ("\" ");
Sb. Append ("\ r \ n");
Sb. Append ("Content-type:");
Sb. Append ("Application/octet-stream");
Sb. Append ("\ r \ n");
Sb. Append ("\ r \ n");
String strpostheader = sb. ToString ();
byte[] postheaderbytes = Encoding.UTF8.GetBytes (Strpostheader); To create a HttpWebRequest object from a URI
HttpWebRequest Httpreq = (HttpWebRequest) webrequest.create (new Uri (address));
Httpreq.method = "POST"; Do not use caching for sent data
Httpreq.allowwritestreambuffering = false; Set time-out for response (300 seconds)
Httpreq.timeout = 300000;
Httpreq.contenttype = "Multipart/form-data; boundary= "+ strboundary;
Long length = fs. Length + postheaderbytes.length + boundarybytes.length;
Long filelength = fs. Length;
httpreq.contentlength = length;
Try
{
progressbar.maximum = Int. MaxValue;
Progressbar.minimum = 0;
Progressbar.value = 0; 4k per upload
int bufferlength = 4096;
byte[] buffer = new Byte[bufferlength]; Number of bytes uploaded
Long offset = 0; Start upload Time
DateTime startTime = DateTime.Now;
int size = r.read (buffer, 0, bufferlength);
Stream Poststream = Httpreq.getrequeststream (); Send Request Header Message
Poststream.write (postheaderbytes, 0, postheaderbytes.length);
while (Size > 0)
{
Poststream.write (buffer, 0, size);
Offset + = size;
Progressbar.value = (int) (offset * (int). Maxvalue/length));
TimeSpan span = datetime.now-starttime;
Double second = span. TotalSeconds;
Lbltime.text = "Elapsed:" + second. ToString ("F2") + "second";
if (Second > 0.001)
{
Lblspeed.text = "Average Speed:" + (Offset/1024/second). ToString ("0.00") + "kb/second";
}
Else
{
lblspeed.text = "Connecting ...";
}
Lblstate.text = "Uploaded:" + (offset * 100.0/length). ToString ("F2") + "%";
Lblsize.text = (offset/1048576.0). ToString ("F2") + "m/" + (filelength/1048576.0). ToString ("F2") + "M";
Application.doevents ();
Size = r.read (buffer, 0, bufferlength);
}
Add a timestamp for the trailer
Poststream.write (boundarybytes, 0, boundarybytes.length);
Poststream.close (); Get the server-side response
WebResponse webrespon = Httpreq.getresponse ();
Stream s = Webrespon.getresponsestream ();
StreamReader sr = new StreamReader (s); Read messages returned by the server side
String sreturnstring = Sr. ReadLine ();
S.close ();
Sr. Close ();
if (sreturnstring = = "Success")
{
returnvalue = 1;
}
else if (sreturnstring = = "Error")
{
returnvalue = 0;
}     }
Catch
{
returnvalue = 0;
}
Finally
{
Fs. Close ();
R.close ();
} return returnvalue;
The parameter description is as follows: Address: The URL of the receiving file, such as: http://localhost/UploadFile/Save.aspx filenamepath: Local file to upload, such as: D:\test.rar   Savename: The name of the file uploaded to the server, such as: 200901011234.rar ProgressBar: A progress bar showing the progress of the file upload. Receive the file WebForm add a save.aspx page, Load method is as follows: protected void Page_Load (object sender, EventArgs e)
{
if (Request.Files.Count > 0)
{
Try
{
Httppostedfile file = Request.files[0];
String FilePath = this. MapPath ("uploaddocument") + "\ \" + file. FileName;
File. SaveAs (FilePath);
Response.Write ("success\r\n");
}
Catch
{
Response.Write ("error\r\n");
}
}
The HttpRuntime to configure the Webconfig file is as follows: WinFormThe code line below//sets the timeout time to get the response (300 seconds)
Httpreq.timeout = 300000;

Also, do not forget to check if the connection timeout for IIS is set to large enough.

Reference:

Http://blogs.msdn.com/johan/archive/2006/11/15/are-you-getting-outofmemoryexceptions-when-uploading-large-files.aspx

Go C # use HttpWebRequest to upload files and show progress under WinForm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.