C # uploading files using HttpWebRequest under WinForm

Source: Internet
Author: User
Tags file upload progress bar

Transferred from: http://blog.csdn.net/shihuan10430049/article/details/3734398

This period of time due to project needs, to achieve WinForm file upload, the personal feel that the use of FTP method is too cumbersome, but also to configure the FTP server, to pass the firewall is also a problem. Originally intended to use the WebClient method, but the implementation of this method, the progress bar after a short time to reach the maximum, to wait for a period of time to transfer complete, if the file is too large (i test about 100M here), there will be an error. Later learned that the original WebClient is loading the entire file into memory before really start uploading, no wonder there will be the previous problem. Have to refer to a lot of articles, a foreigner's article on my inspiration is very big (http://blogs.msdn.com/johan/archive/2006/11/15/ are-you-getting-outofmemoryexceptions-when-uploading-large-files.aspx), is implemented using the HttpWebRequest method. Cut the crap and start getting to the point. The implementation process is as follows:

In WinForm, call the following method to upload the file:

 //<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" >name of file after uploading</param>        /// <param name= "ProgressBar" >Upload progress bar</param>        /// <returns>successfully returned 1, failed to return 0</returns>        Private intUpload_request (stringAddressstringFilenamepath,stringSavename, ProgressBar ProgressBar) {            intReturnValue =0; //the file to uploadFileStream fs =NewFileStream (Filenamepath, FileMode.Open, FileAccess.Read); BinaryReader R=NewBinaryReader (FS); //time Stamp            stringStrboundary ="----------"+ DateTime.Now.Ticks.ToString ("x"); byte[] boundarybytes = Encoding.ASCII.GetBytes ("/r/n--"+ Strboundary +"/r/n"); //Request header InformationStringBuilder SB =NewStringBuilder (); 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"); stringStrpostheader =sb.            ToString (); byte[] Postheaderbytes =Encoding.UTF8.GetBytes (Strpostheader); //to create a HttpWebRequest object from a URIHttpWebRequest Httpreq = (HttpWebRequest) webrequest.create (NewUri (address)); Httpreq.method="POST"; //do not use caching for sent dataHttpreq.allowwritestreambuffering =false; //set time-out for response (300 seconds)Httpreq.timeout =300000; Httpreq.contenttype="multipart/form-data; boundary="+strboundary; LongLength = fs. Length + postheaderbytes.length +boundarybytes.length; LongFilelength =FS.            Length; Httpreq.contentlength=length; Try{progressbar.maximum=int.                MaxValue; Progressbar.minimum=0; Progressbar.value=0; //4k per upload                intBufferlength =4096; byte[] buffer =New byte[Bufferlength]; //number of bytes uploaded                Longoffset =0; //Start upload TimeDateTime StartTime =DateTime.Now; intSize = R.read (buffer,0, bufferlength); Stream Poststream=Httpreq.getrequeststream (); //Send Request Header messagePoststream.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; DoubleSecond =span.                    TotalSeconds; Lbltime.text="Elapsed:"+ second. ToString ("F2") +"seconds"; if(Second >0.001) {Lblspeed.text="Average Speed:"+ (Offset/1024x768/second). ToString ("0.00") +"kb/sec"; }                    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 trailerPoststream.write (Boundarybytes,0, boundarybytes.length);                Poststream.close (); //get the server-side responseWebResponse webrespon =Httpreq.getresponse (); Stream s=Webrespon.getresponsestream (); StreamReader SR=NewStreamReader (s); //read messages returned by the server sideString 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 (); }            returnreturnvalue; }

The parameters are described as follows:

Address: The URL of the received file, such as: http://localhost/UploadFile/Save.aspx

Filenamepath: The local file to be uploaded, such as: D:/test.rar

Savename: The name of the file uploaded to the server, such as: 200901011234.rar

ProgressBar: Shows the progress of file upload progress bar.

To receive the file WebForm add a save.aspx page, the Load method is as follows:

protected voidPage_Load (Objectsender, EventArgs e) {            if(Request.Files.Count >0)            {                Try{httppostedfile file= request.files[0]; stringFilePath = 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:

You can only upload 4 m if you can't. If you want to upload a larger file, Maxrequestlength,executiontimeout set it larger, while the code line under WinForm

Set time-out for response (300 seconds)
Httpreq.timeout = 300000;

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

Everything is well-configured, and the results are as follows:

In order to solve this problem, I looked at a lot of articles, in this, later encountered the same problem there is a place to find.

C # uploading files using HttpWebRequest under WinForm

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.