Upload files to the server through the HTTP protocol in WinForm

xiaoxiao2021-03-06  84

I believe that using ASP.NET writes a web page for uploading files. Everyone will write, but have anyone thinks to upload files through the HTTP protocol through the WinForm?

Some people say that the file is to be on the server, isn't it very simple to use the FTP protocol? The efficiency is high, why should I use the HTTP agreement so trouble? There are several reasons this:

(1) The deployment of the FTP server is relatively trouble, but also set permissions, permission settings are incorrect, will also provoke a series of security issues.

(2) If both parties have a firewall, do not want to develop some of the FTP-related ports, http will be used in the big use, just like web services to penetrate the firewall.

(3) Other ..., still thinking ...

But use HTTP and some of his problems, such as can't be broken, it is difficult to upload big files, slow speed, so the file size uploaded by HTTP protocol should not be too big.

Said so much, original home, in general, there are several optional methods to upload files in WinForm:

(1) The web services mentioned earlier is a good way to write a webMethod, including the parameters of the byte [] type, then call the web services method, the file content is transmitted to the server on the server. , Then re-save it.

[WebMethod] public void uploadfile (byte [] content, string filename) {stream sw = new streamwriter (...); SW.CLOSE ();} Of course, this method of efficiency through Base64 encoding is relatively low, then it can be used WSE, support attachments, and transferred in 2-en-enamded forms, efficiency will be higher. (2) In addition to the WebService, another simple method is to simulate the POST action of HTTP through WebClient or HttpWebRequest. At this time, you first need to write an ASP.NET web form to respond to upload, the code is as follows: <% @ page language = "c #" codebehind = "Webform1.aspx.cs" autoeventwireup = "false" inherits = "UploadFileWebformForm1"%> Webform1 </ title> <meta name = "generator" content = "Microsoft Visual Studio .NET 7.1 "> <meta name =" CODE_LANGUAGE "Content =" C # "> <meta name =" vs_defaultClientScript "content =" JavaScript "> <meta name =" vs_targetSchema "content =" http://schemas.microsoft.com/intellisense / IE5 "> </ head> <body> <form id =" form1 "method =" post "runat =" server "> </ form> </ body> </ html> using system; using system.collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls ;</p> <p>A summary description of Namespace UploadFileWeb {/// <summary> /// WebForm1. /// </ 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);} /// <summary> /// Designer Supports the required method - Do not use the code editor to modify the // / this method. /// </ summary> private void initializecomponent () {this.load = new system.eventhandler (this.page_load);} #ENDREGON}}</p> <p>In fact, this page is the same as our usual written ASP.NET upload file code. In the REQUEST object in the web page, this object contains this object, which contains information on all files uploaded by the Post method. It is called the Request.Files [i] .saves method.</p> <p>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/javast/javastart2.exe");}</p> <p>Is it very simple? It is really so simple.</p> <p>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));</p> <p>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 ) 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 ();</p> <p>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</p> <p>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 it Others' code) Public class wwhttp {/// <summary> /// Fires Progress Events When Url. /// </ summary> public event onreceivedatahandler onRecEada; /// <summary> / // DETERMINESHOW DATA IS POSTED WHEN CPOSTBUFFER IS set. /// 1 - Urlencoded /// 2 - Multi-Part Form Vars /// 4 - XML ​​(Raw Buffer Content Type: Text / XML) /// </ summary > Public int postmode {get {returnim}} set {this.npostmode = value;}} /// <summary> /// user name buy for authentication. // // t use the currently logged in User When Accessing An NTLM Resource You CAN Use "Autologin". /// </ summary> public string username {get {return this.cusername;} set {cusername = value;}} /// <summary> /// password for authentication./// </ summary> public string password {get {return this.cpassword;} set {this.cpassword = value;}} /// <summary> /// address of the proxy server to be used. /// Use optional dEFAULTPROXY value to specify that you want to IE's Proxy Settings /// </ summary> public string ProxyAddress {get {return this.cProxyAddress;} set {this.cProxyAddress = value;}} /// <summary> // / SMICOLON SEPARATED ADDRESS LIST OF THE Servers The Proxy IS Not Used for. /// </ summary> public string proxybypass {get {return this.cproxybypass</p> <p>} Set {this.cproxybyPass = value;}} /// <summary> /// username for a password validating proxy. ONLY Used if the proxy info is set. /// </ summary> public string proxyusername {get {return this.cProxyUsername;} set {this.cProxyUsername = value;.}} /// <summary> /// password for a password validating Proxy Only used if the proxy info is set /// </ summary> public string ProxyPassword. {Get {return;} set {this.cproxyPassword = value;}} /// <summary> /// Timeout for the web request in seconds. Times out on connections, read and send Operations. /// default IS 30 seconds. /// </ summary> public int Timeout {get {returnşnConnectTimeout;} set {this.nconnecttimeout = value;}} /// <summary> /// error message if the error flag is set OR An Error Value Is Returned from a Method. /// </ summary> public string errormsg {get {return this.crrormsg;} set {this.cerrormsg = value;}} /// <summary> /// error flagIF An error {rary this.berror = value;}} /// <Summary> /// determines WHETERERORS 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) /// </ summary> public bool throwExceptions {get {return bThrowExceptions..; } Set {this.bthrowexceptions = value;}}} /// <summary> /// if set to a non-zero value will automaticly track cookies. The number assigned is the cookie count. /// </ summary></p> <p>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 nConnectTimeout = 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 //} /// <summary> /// Adds post form variables to the request buffer. ///////////n ' "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) /// taher - Raw Content Buffer. Just Assign To Key. /// <</p> <p>/ summary> /// <param name = "key"> key value or raw buffer depending on post type </ param> /// <param name = "value"> value to store. Used Only In Key / Value PAIR MODES </ 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) {case 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); this.opostdata.write (Encoding.Getencoding (1252) .Getbytes ("/ r / n")); Break; D Efault: this.opostdata.write (value); Break;}} public void addressKey (String Key, String Value) {this.addpostKey (key, encoding.getencoding (1252));} /// < Summary> /// adds a fully self Contained Post Buffer to the request. /// Works for xml or previously encoded content. /// </ summary> /// <param name = "postbuffer> </ param> public Void AddPostKey (String FullPostBuffer) {this.opostData.write (Encoding.Getencoding (1252) .getbytes (FullPostBuffer);</p> <p>} 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). Gettes ("-" 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;} /// <summary> /// Return a the result from an http url insto a streamreader. ///client code SHOULD CALL Close () on the return Object when done reading. /// </ summary> /// <param name = "URL"> URL TO RETRIEVE. </ param> /// <param name = "WebRequest"> An HttpWebRequest object that can be passed in with properties preset </ param> /// <returns> </ returns> protected StreamReader GetUrlStream (string Url, HttpWebRequest Request) {try {this.bError = false;. this.cErrorMsg = " "; If (request == null) {request = (httpwebrequest) system.net.WebRequest.create (URL);</p> <p>} 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.GetDefaultProxy ();} 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 any if (this.opostdata! = Null) {Request.Method = "post"; switch (Switch); THIS.NPOSTMODE) {casse 1: request.contenttype = "Application / X-www-form-urlencoded"; // Strip Off ANY TRAILING &</p> <p>Which can 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 / R / N ")); Break; Case 4: Request.conteTtype =" text / xml "; Break; default: goto case 1;} stream lopostdata = request.getRequestStream (); //lopostdata.write (LCPostData ,0 ,lcpostdata. Length); this.oPostStream.WriteTo (loPostData); byte [] buffer = new byte [this.oPostStream.Length]; buffer = this.oPostStream.ToArray (); Console.Write (Encoding.GetEncoding (1252) .GetString ( Buffer, 0, buffer.length); // *** close the memory stream this.opostStream.close (); this.opoststream = null; // *** Close the binary WRI Ter 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.ocookies = response.cookies;</p> <p>} 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; try {ix (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.Message Iberror = true; return null;}} /// <summary> /// Return a the result from an HTTP URL INTO A streould Call Close () on the returned Object When Done Reading . /// </ summary> /// <param name = "URL"> URL TO RETRIEVE. </ Param> /// <Returns> </ returns> public streamreader geturlstream (string URL) {httpwebrequest ohttpwebrequest =</p> <p>null; return this.GetUrlStream (Url, oHttpWebRequest);} /// <summary> /// Return a the result from an HTTP Url into a StreamReader /// Client code should call Close () on the returned object when done. reading. /// </ summary> /// <param name = "Request"> A Request object </ param> /// <returns> </ returns> public StreamReader GetUrlStream (HttpWebRequest Request) {return this.GetUrlStream ( Request.Requesturi.absoluteuri, request);} /// <summary> /// Return a the result from an HTTP URL INTO A STRING. /// </ summary> /// <param name = "URL"> URL to retrieve </ param> /// <returns> </ returns> public string GetUrl (string Url) {StreamReader oHttpResponse = this.GetUrlStream (Url);. if (oHttpResponse == null) return ""; string lcResult = oHttpResponse .ReadtpResponse.close (); Return LCRESULT;} /// <summary> /// Return a the result from an HTTP URL INTO A STRING. /// </ summary> /// <parame = "URL"> URL to RETRIEVE. </ Param> /// <Returns> </ returns> P ublic byte [] GetUrlBytes (string Url) {StreamReader oHttpResponse = this.GetUrlStream (Url); if (oHttpResponse == null) {return null;} string lcResult = oHttpResponse.ReadToEnd (); oHttpResponse.Close (); return null; } /// <summary> /// Retrieves url with events in the onreceivedata event. /// </ summary> /// <param name = "URL"> </ param> /// <param name = "buffersize "> </ param> /// <returns> </ returns></p> <p>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 ; lntotalbytes = lnsize; // *** raise an Event if hooded upiff (this.onreceiveData! = Null) {/// *** Update The Event Handler Oargs.currentBytecount = LNTOTALBYTES; OARGS.NUMBEROFREADS = LNCOU nt; Oargs.currentchunk = LCTEMP; this.onreceivedata (this, OARGS); // *** Check for cancelled flagiff}}}}}}}}}}} // While CloseDown: OHTTPRESPRESE.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 ();} public delegate void OnReceiveDataHandler (object sender, OnReceiveDataEventArgs e); public class OnReceiveDataEventArgs {public long CurrentByteCount = 0;</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-122503.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="122503" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.047</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'u_2BWEZs9ebzz47OjJkIVG_2FLlH4mTLnAWqYsc0U31zWBQASXxxuaFkCtC0XRHq8PqYV5eyk6lxgJ873moMrs4wjw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>