/// WebForm1 summary description. /// summary> public class Webform1: system.Web.ui.page {private void page_load (object sender, system.eventargs e) {// Place the user code here to initialize the page foreach (String F in Request). FILES.ALLKEYS) {httppostedfile file = request.files [f]; file.saves (@ "d: / temp /" file.filename);} if (Request.Params ["testkey"]! = Null) {response .Write (Request.Params ["TestKey"]);}} #Region Web Form Designer Generated Code Override Protected Void OnNit (Eventargs E) {// // Codegen: This call is an ASP.NET web form design The device is required.
// InitializeComponent (); base.onit (e);} /// /// Designer Supports the required method - Do not use the code editor to modify the // / this method. /// summary> private () {this.load = new system.eventhandler (this.page_load);} #ENDREGON}} In fact, this page is the same as our usual written ASP.NET upload file code. In the Request object in the web page, the object contains this object, which contains information on all files uploaded by the Post method. At this time, what is needed is to call the Request.Files [i] .saves method. But how can you only simulate Web Form Post data in WinForm? Two very useful classes are provided in the System.Net namespace, one is WebClient, and the other is the HTTPWebRequest class. If we don't need to upload files through the proxy server, it is very simple, just simply call the WebClient.uploadFile method to upload files: private void button1_click (Object sender, system.eventargs e) {WebClient mywebclient = new WebClient () MyWebClient.uploadFile ("http://localhost/uploadfileweb/webform1.aspx", "post", @ "d: /temp/java/javastart/javastart2.exe");} Is it very simple? It is really so simple.
But what should I do if I want to upload through the proxy server? Then need to use HttpWebRequest, but this class does not have an UPLOAD method, but after we compile the WebClient.uploadFile method through the Reflector, we found that it is also implemented inside the WebRequest, the code is as follows: public byte [] UploadFile string address, string method, string fileName) {string text1; string text2; WebRequest request1; string text3; byte [] buffer1; byte [] buffer2; long num1; byte [] buffer3; int num2; WebResponse response1; byte [] buffer4 DateTime Time1; Long Num3; String [] TextArray1; FileStream Stream1 = NULL; Try {filename = path.getFullPath (filename); time1 = datetime.now; num3 = time1.ticks; text1 = "------ -------------- " Num3.toString (" x "); if (this.m_headers == null) {this.m_headers = new WebHeaderCollection ();} text2 = this.m_headers ["Content-type"]; if (text2! = Null) {if (text2.tolower (CultureInfo.invariantculture) .StartSwith ("Multipart /")) {throw new WebException ("net_webclient_multipart");}} else {text2 = "Application / OcTeet-stream";} this.m_headers ["Content-Type"] = "Multipart / form-data; boundary = " text1; this.m_responseHeaders = null; stream1 = new FileStream (fileName, FileMode.Open, FileAccess.Read); request1 = WebRequest.Create (this.GetUri (address));
request1.Credentials = this.Credentials; this.CopyHeadersTo (request1); request1.Method = method; textArray1 = new string [7]; textArray1 [0] = "-"; textArray1 [1] = text1; textArray1 [2] = "/ r / nContent-disposition: form-data; name = /" file / "; filename = /" "; TextArray1 [3] = path.getFileName (filename); TextArray1 [4] =" / "/ r / Ncontent-type: "; TextArray1 [5] = text2; TextArray1 [6] =" / r / n / r / n "; Text3 = String.concat (TextArray1); buffer1 = Encoding.utf8.getbytes (Text3); buffer2 = Encoding.ascii.getbytes ("/ r / n -" text1 "/ r / n"); Num1 = 9223372036854775807; Try {Num1 = stream1.length; request1.contentLength = ((Num1 (((long) Buffer1.Length)) ((long) buffer2.Length);} catch {} buffer3 = new byte [math.min ((int) 8192), ((int) Num1) )]; Use (stream stream2 = request1.getRequestStream ()) {stream2.write (buffer1, 0, buffer1.Length); do {Num2 = stream1.read (buffer3, 0, buffer3.length); if (Num2! = 0) {stream2.write (Buffer3, 0, Num2);}} while ((Num2! = 0)); stream2.write (buffer2, 0, buffer2.Length);} stream1.close ();
stream1 = null; response1 = request1.GetResponse (); this.m_responseHeaders = response1.Headers; return this.ResponseAsBytes (response1);} catch (Exception exception1) {if (stream1 = null!) {stream1.Close (); stream1 = null;} if ((exception1 is WebException) || (exception1 is SecurityException)) {throw;} throw new WebException (SR.GetString ( "net_webclient"), exception1);} return buffer4;} in this code, but in fact The most critical is how to simulate the POST request, by analyzing the code and monitor HTTP, we can find that the Simulated POST format is as follows: ---------------------- 8C64F47716481F0 / / Timestamp Content-Disposition: Form-Data; Name = "File"; filename = "a.txt" // file name content-type: Application / OCTET-stream // file content -------- --------------- 8C64F47716481F0 At this time, we only need to code to simulate such a set of data (we can also learn from the MS code), the following is the code (declaration, I borrowed someone else's code) Public Class WWHTTP {/// Fires Progress Events When Using geturLevents () to Retrieve A URL. Public Event OnRecate; /// DETERMINESHOW DATA IS POSTED WHEN CPOSTBUFFER IS SET. // 1 - Urlencoded /// 2 - Multi-Part Form Vars /// 4 - XML (Raw Buffer Content Type: Text / XML) public int PostMode {get {return this.nPostMode;} set {this.nPostMode = value;}} /// User name used for Authentication /// To use the currently logged in user when accessing an NTLM resource you can use ". Autologin ". Public string username {get {return this.cusername;} set {cusername = value;
.}} /// Password for Authentication public string Password {get {return this.cPassword;} set {this.cPassword = value;}} /// Address of the Proxy Server to be used /// Use optional DEFAULTPROXY value. to specify that you want to IE's Proxy Settings public string ProxyAddress {get {return this.cProxyAddress;} set {this.cProxyAddress = value;}} /// Semicolon separated Address list of the servers the proxy is not used for public string. ProxyBypass {get {return this.cProxyBypass;} set {this.cProxyBypass = value;}}. /// Username for a password validating Proxy Only used if the proxy info is set public string proxyUsername {get {return this.cProxyUsername.; } set {this.cProxyUsername = value;.}} /// password for a password validating Proxy Only used if the proxy info is set public string ProxyPassword {get {return this.cProxyPassword;.} set {this.cProxyPassword = value; }} /// Timeout for the Web Request in Seconds. Times O ut on connection, read and send operations /// Default is 30 seconds public int Timeout.. {get {return this.nConnectTimeout;} set {this.nConnectTimeout = value;}} /// Error Message if the Error Flag is set or an error value is returned from a method public string ErrorMsg {get {return this.cErrorMsg;} set {this.cErrorMsg = value;}}.. /// error flag if an error occurred public bool error {get {return this .Berror;} set {this.berror = value;
}} /// Determines whether errors cause exceptions to be thrown. By default errors /// are handled in the class and the Error property is set for error conditions. /// (not implemented at this time). Public bool ThrowExceptions { get {return bThrowExceptions;} set {this.bThrowExceptions = value;}.} /// If set to a non-zero value will automatically track cookies The number assigned is the cookie count public bool HandleCookies {get {return this.bHandleCookies. ;} set {this.bHandleCookies = value;}} public CookieCollection Cookies {get {return this.oCookies;} set {this.Cookies = value;}} public HttpWebResponse WebResponse {get {return this.oWebResponse;} set {this. oWebResponse = value;}} public HttpWebRequest WebRequest {get {return this.oWebRequest;} set {this.oWebRequest = value;}} // *** member properties // string cPostBuffer = ""; MemoryStream oPostStream; BinaryWriter oPostData; int NPOSTMODE = 1; INT NCO nnectTimeout = 30; string cUserAgent = "West Wind HTTP .NET"; string cUsername = ""; string cPassword = ""; string cProxyAddress = ""; string cProxyBypass = ""; string cProxyUsername = ""; string cProxyPassword = "" ; bool bThrowExceptions = false; bool bHandleCookies = false; string cErrorMsg = ""; bool bError = false; HttpWebResponse oWebResponse; HttpWebRequest oWebRequest; CookieCollection oCookies; string cMultiPartBoundary = "--------------- -------------- 7CF2A327F01AE ";
Public void WWHTTP () {// // Todo: Add Constructor Logic Here / //} // Adds Post Form Variables To The Request Buffer DETERMINESHOW PARMS Are Handled. /// 1 - Urlencoded Form Variables. Uses Key and Value Pairs (IE. "Name", "Rick") to create urlencoded content /// 2 - Multi-Part Forms - Not supported /// 4 - XML block - Post a single xml block. Pass in as key (1st Parm) ///} - Raw Content Buffer. Just Assign To Key. /// summary> /// key value or raw buffer depending on post type param> / // Value to store. Used online in key / value pair model param> public void addpostkey (string key, byte [] value) {if (this.opostdata == null) {this .oPostStream = new MemoryStream (); this.oPostData = new BinaryWriter (this.oPostStream);} if (Key == "RESET") {this.oPostStream = new MemoryStream (); this.oPostData = new BinaryWriter (this.oPostStream } Switch (this.npostmode) {casse 1: this.opostdata.write (Encoding.Getencoding (1252) .getbytes (key "=" system.web.httputility.urlencode (value) "&")); break; case 2: this.opostData.write (Encoding.Getencoding (1252) .GetBytes ("-" this.cmultipartboundary "/ r / n" "content-disposition: form-data; name = /" " key " / "/ r / n / r / n ")); this.opostdata.write (value); concered.Getencoding (1252) .getbytes (" / r / n ")); break; default: this.opostdata.write Value;
}}} Public void addpostkey (String Key, String Value) {this.addpostKey (KEY, Encoding.Getencoding (1252) .GetBytes (Value));} /// Adds a fully self Contained Post Buffer to the request. /// Works for XML or previously encoded content /// param> public void AddPostKey (string FullPostBuffer) {this.oPostData.Write (Encoding.GetEncoding (1252) .GetBytes (FullPostBuffer)).; } public bool AddPostFile (string Key, string FileName) {byte [] lcFile; if (this.nPostMode = 2!) {this.cErrorMsg = "File upload allowed only with Multi-part forms"; this.bError = true; return False;} try {filestream (filename, system.io.filemode.open, system.io.filemode. open, system.io.fileaccess.read; lcfile = new byte; lofile.length; Lofile.Read (Lcfile, 0, (INT) ); lofile.close ();} catch (exception e) {this.cerrormsg = E.MESSAGE; this.berror = true; return false;} this.opostdata.write (Encoding.Getencoding) (1252) .Getbytes ("-" this.cmultipartboundary "/ r / n" "content-disposition: form-data; name = /" " key " / "filename = /" new fileInfo (FILENAME) .NAME "/" / r / n / r / n "))); this.opostdata.write (lcfile); this.opostData.write (Encoding.Getencoding (1252) .getbytes (" / r / n ")); Return true;} /// Return a the result from an http url into a streoulder. ///Client code sales. /// Client Code Should Call Close () on the return. /// Url to Retrieve. Param> ///
An HttpWebRequest object that can be passed in with properties preset param> /// returns> protected StreamReader GetUrlStream (string Url, HttpWebRequest Request) {try {this.bError = false;. This.cErrorMsg = " "; If (request == null) {request = (httpwebrequest) system.net.WebRequest.create (URL);} Request.USERAGENT = this.cuserAgent; request.timeout = this.nconnectTimeout * 1000; // *** Save for external access this.oWebRequest = Request; // *** Handle Security for the request if (this.cUsername.Length> 0) {if (this.cUsername == "aUTOLOGIN") Request.Credentials = CredentialCache.DefaultCredentials; else Request.Credentials = new NetworkCredential (this.cUsername, this.cPassword);} // *** Handle Proxy Server configuration if (this.cProxyAddress.Length> 0) {if (this.cProxyAddress == "dEFAULTPROXY") { Request.proxy = new webproxy (); request.proxy = webproxy.getDefau ltProxy ();} else {WebProxy loProxy = new WebProxy (this.cProxyAddress, true); if (this.cProxyBypass.Length> 0) {loProxy.BypassList = this.cProxyBypass.Split ( ';');} if (this .cProxyUsername.Length> 0) loProxy.Credentials = new NetworkCredential (this.cProxyUsername, this.cProxyPassword); Request.Proxy = loProxy;}} // *** Handle cookies - automatically re-assign if (this.bHandleCookies) { Request.cookieContainer = new cookiecontainer (); if (this.ocookies! = Null && this.ocookies.count>
0) {Request.cookieContainer.Add (this.ocookies);}} // *** DEAL with the post buffer if anyness (this.opostdata! = Null) {Request.Method = "post"; switch (this. NPOSTMODE) {casse 1: request.contentType = "Application / X-www-form-urlencoded"; // Strip Off ANY TRALING & Which Cause Cause Problems with some // http servers //iff (this.cpostbuffer.endswith) & ")) // this.cpostbuffer = this.cpostbuffer.substring (0, this.cpostbuffer.Length-1); break; case 2: request.contentType =" Multipart / form-data; boundary = " this.cmultipartboundary This.opostdata.write (Encoding.Getencoding (1252) .GetBytes ("-" this.cmultipartboundary "/ r / n")); break; case 4: request.contentType = "text / xml"; BREAK Default: goto case 1;} stream lopostdata = request.getRequestStream (); //lopostdata.write(LCPostData ,0 ,lcpostdata.length); this.opostStream.writto (L OpostData); BYTE [] Buffer = new byte [this.opostStream.length]; buffer = this.opostStream.toArray (); console.write (1252) .getstring (buffer, 0, buffer.length) ; // *** close the memory stream this.opoststream.close (); this.opoststream = null; // *** close the binary writer this.opostdata.close (); this.opostdata = null; // * ** Close Request Stream LopostData.close (); // *** Clear The Post Buffer //this.cpostbuffer = "";} // *** Retrieve The Response Headers httpwebresponse response =
(Httpwebresponse) Request.getResponse (); // ** save cookies the server sends if (this.bHandlecookies) {if (response.cookies.count> 0) {if (this.ocookies == null) {this.ocOooties = Response.Cookies;} else {// ** If we already have cookies update the list foreach (Cookie oRespCookie in Response.Cookies) {bool bMatch = false; foreach (Cookie oReqCookie in this.oCookies) {if (oReqCookie.Name = = ORESPCOOKIE.NAME) {OreqCookie.Value = orespcookie.name; bmatch = true; break; //}} // for Each ReqCookies if (! bmatch) this.ocookies.add (orespcookie);} // for Each Response. Cookies} // this.cookies == null} // if Response.cookie.count> 0} // if this.bHandlecookies = 0 // *** save the response object for external access this.OWebResponse = response; Encoding ENC { if (Response.ContentEncoding.Length> 0) enc = Encoding.GetEncoding (Response.ContentEncoding); else enc = Encoding.GetEncoding (1252);} catch {// *** Invalid encoding passed enc = Encoding.GetEncoding (1252) ;} // *** drag to a stream StreamReader strResponse = new StreamReader (Response.GetResponseStream (), enc); return strResponse;} catch (Exception e) {if (this.bThrowExceptions) throw e; this.cErrorMsg = e Iver; iberror = true; return null;
}}} /// Return A The Result from an HTTP URL INTO A streamreader. /////// URL TO RETRIEVE. param> /// returns> public StreamReader GetUrlStream (string Url) {HttpWebRequest oHttpWebRequest = null; return this.GetUrlStream (Url, oHttpWebRequest);} /// return a the result from an HTTP Url into A streamreader. /// Client Code Should CLOSE () on the return Object when Done Reading. // a Request Object param> /// returns> public StreamReader GetUrlStream (HttpWebRequest Request) {return this.GetUrlStream (Request.RequestUri.AbsoluteUri, Request);}. /// return a the result from an HTTP Url into a string /// Url to Retrieve. param> /// returns> public string geturl (string URL) {streamreader ohttpresponse = this.geturlStream (URL); if (ohttpResponse == null) return "; string lcResult = OHTTPRESPONSE.READTOEND (); OHTTPRESPONSE.CLOSE (); Return LCRESULT;} /// Return A THE RESRING. // URL TO RETRIEVE. param > /// returns> public byte [] GetUrlBytes (string Url) {StreamReader oHttpResponse = this.GetUrlStream (Url); if (oHttpResponse == null) {return null;} string lcResult = oHttpResponse.ReadToEnd ( ); Httpresponse.close (); return null;} /// Retrieves URL with event. // <
/ Param> /// param> /// returns> public string GetUrlEvents (string Url, long BufferSize) {StreamReader oHttpResponse = this.GetUrlStream (Url); if (oHttpResponse == null) return ""; long lnSize = BufferSize; if (this.oWebResponse.ContentLength> 0) lnSize = this.oWebResponse.ContentLength; else lnSize = 0; Encoding enc = Encoding.GetEncoding (1252); StringBuilder loWriter = new StringBuilder ((int) lnSize); char [] lcTemp = new char [BufferSize]; OnReceiveDataEventArgs oArgs = new OnReceiveDataEventArgs (); oArgs.TotalBytes = lnSize; lnSize = 1; int lnCount = 0; long lnTotalBytes = 0; while (lnsize> 0) {lnsize = OHTTPRESPONSE.READ (lcTemp, 0, (int) buffersize; if (lnsize> 0) {Lowriter.Append (lcTemp, 0, (int)); lncount ; lnototalbytes = lnsize; // *** raise an event if hooded upiff (this.onreceiveData! = Null) {/// *** Update the Event Handler oArgs.CurrentByteCount = lnTotalBytes; oArgs.NumberOfReads = lnCount; oArgs.CurrentChunk = lcTemp; this.OnReceiveData (this, oArgs); // *** Check for cancelled flag if (oArgs.Cancel) goto CloseDown;}}} // While closedown: ohttpresponse.close (); // *** send Done Notification if (this.onreceiveData! = null&&! oargs.cancel) {// *** Update the Event Handler OARGS.DONE = true; this.onreceiveData (this, OARGS);} // Return LCHTML; RETURN Lowriter.toString ();