本文實例講述了js+ajax實現獲取文件大小的方法。分享給大家供大家參考,具體如下:
顧名思義,通過JS和Ajax來獲取上傳文件的大小,在上傳之前可以有個判斷,對上傳的文件有所控制,因為js控制文件大小(JS獲取文件大小)有些問題,具體大家試下就知道了,在此整理了一下ajax的獲取文件大小的方法,比較好用,再調試過程中,出現了c:/fakepath/ 的錯誤,也將解決方案羅列在下面,以供大家參考
廢話少說,代碼如下
JS如下:
<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>
後台C#代碼:
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(); } }
完整實例代碼點擊此處本站下載。
希望本文所述對大家JavaScript程序設計有所幫助。