Home >Web Front-end >JS Tutorial >js ajax method to obtain file size_javascript skills
The example in this article describes the method of obtaining the file size through js ajax. Share it with everyone for your reference, the details are as follows:
As the name suggests, you can get the size of the uploaded file through JS and Ajax. You can make a judgment before uploading and control the uploaded file, because there are some problems with js controlling the file size (JS getting the file size). Please give it a try. That’s it. I’ve sorted out the ajax method of obtaining the file size. It’s relatively easy to use. During the debugging process, an error of c:/fakepath/ occurred. The solution is also listed below for your reference
No further nonsense, the code is as follows
JS is as follows:
<script language="Jscript"> function chksize(){ var ticketType = "Oil"; var file1=document.getElementById("txtfile"); var v = file1.value; file1.select(); var realpath = document.selection.createRange().text; var input = "<Record><Type>TicketLoanResult</Type><TicketType>" + realpath + "</TicketType></Record>"; var objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); objXmlHttp.Open("POST", "XMLHttpPost.aspx", false); objXmlHttp.Send(input); var returnXml = objXmlHttp.responseText; if(returnXml!=null) { returnXml=parseInt(returnXml/1024/1024); } alert(returnXml); return false; } </script>
Backend C# code:
public partial class XMLHttpPost : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { XmlDocument xmlDocumenet = new XmlDocument(); xmlDocumenet.Load(Request.InputStream); string type = xmlDocumenet.SelectSingleNode("descendant::Type").InnerText; string returnMessage = string.Empty; switch (type.Trim()) { case "TicketLoanResult": returnMessage = GetTicketLoanResult(xmlDocumenet); break; default: break; } Response.ContentType = "text/xml"; Response.Write(returnMessage); } catch (Exception exceptional) { //如果有錯誤則返回錯誤信息(Xml格式) string errorMessage = "<Error>" + exceptional.Message + "</Error>"; Response.ContentType = "text/xml"; Response.Write(errorMessage); } finally { Response.End(); } } private string GetTicketLoanResult(XmlDocument input) { XmlNode item = input.SelectSingleNode("descendant::TicketType"); string ticketType = item.InnerText.Trim(); FileStream stream = new FileStream(ticketType,FileMode.Open); return stream.Length.ToString(); } }
Click here for the complete example codeDownload from this site.
I hope this article will be helpful to everyone in JavaScript programming.