C # Use httpwebrequest in winform to upload files and display the progress
During this time, due to project requirements, it is too troublesome to upload files under winform, and you have to configure the FTP server through the firewall. I was planning to use the WebClient method, but after using this method, the progress bar will reach the maximum value in a short time. It takes a while to complete the transfer, if the file is too large (I tested it for about 100 MB), an error will occur. It was later known that the original WebClient started uploading only after loading the entire file to the memory. No wonder the previous problem may occur. I had to refer to a lot of articles, a foreigner's article inspired me a lot (http://blogs.msdn.com/johan/archive/2006/11/15/are-you-getting-outofmemoryexceptions-when-uploading-large-files.aspx), is implemented using the httpwebrequest method. Start to get started. The implementation process is as follows:
In winform, call the following method to upload files:
/// <Summary> /// upload the local file to the specified server (httpwebrequest method) /// </Summary> /// <Param name = "Address"> the server to which the file is uploaded </param> /// <Param name = "filenamepath"> to upload local file (full path) </param> /// <Param name = "savename"> name of the uploaded file </param> /// <Param name = "progressbar"> upload progress bar </Param >/// <returns> 1 is returned successfully, 0 </returns> private int upload_request (string address, string filenamepath, string savename, progressbar) {int returnvalue = 0; // file to be uploaded filestream FS = new filestream (filenamepath, filemode. open, fileaccess. read); binaryreader r = new binaryreader (FS); // timestamp 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); // create an httpwebrequest object httpwebr Based on the URI Equest httpreq = (httpwebrequest) webrequest. create (New uri (Address); httpreq. method = "Post"; // do not use the httpreq cache for sent data. allowwritestreambuffering = false; // sets the response timeout (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; // 4 K int bufferlength = 4096 for each upload; byte [] buffer = new byte [bufferlength]; // Number of uploaded bytes long offset = 0; // start upload time datetime starttime = datetime. now; int size = R. read (buffer, 0, bufferlength); stream poststream = httpreq. getrequeststream (); // send the 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 = "in use:" + second. tostring ("F2") + "seconds"; 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 the end timestamp poststream. write (boundarybytes, 0, boundarybytes. length); poststream. close (); // obtain the server response webresponse webrespon = httpreq. getresponse (); stream S = webrespon. getresponsestream (); streamreader sr = new streamreader (s); // read the message string sreturnstring = Sr returned by the server. 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 ;}
Parameters are described as follows:
Address: the URL of the received file, for example, http: // localhost/uploadfile/Save. aspx.
Filenamepath: local file to be uploaded, for example, D: \ test.rar
Savename: the name of the file uploaded to the server, for example, 20090102.1634.rar
Progressbar: displays the progress bar of the file upload progress.
Add a save. ASPX page to the webform of the received file. The 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"); } } }
At the same time, you need to configure the httpruntime of the webconfig file as follows:
<Httpruntime maxrequestlength = "102400" executiontimeout = "300"/>
If not, you can upload up to 4 MB of data. If you want to upload a larger file, set maxrequestlength and executiontimeout to a larger value, and set the code line in winform.
// Set the response timeout (300 seconds)
Httpreq. Timeout = 300000;
You must also modify the settings. Also, do not forget to check whether the connection timeout value of IIS is set to large enough.
Everything is configured, and the running effect is as follows: