30
DecGet file size before upload using jquery
File uploading functionality is generally used by the developers. Before uploading file on the server, to know the size of file is a good practice. By knowing file size, we can restrict the end user to upload large size files on the server since we have limited space on the server. We should check uploaded file size on server side as well client side. In this article I am going to expose how you can get size of file before uploading on client side using JQuery. For more help refer the article Asp.Net asynchronous file upload using jquery.
Example to get file size before upload using JQuery
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Get File Size</title> <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript" > </script> <script type="text/javascript"> function GetFileSize(fileid) { try { var fileSize = 0; //for IE if ($.browser.msie) { //before making an object of ActiveXObject, //please make sure ActiveX is enabled in your IE browser var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value; var objFile = objFSO.getFile(filePath); var fileSize = objFile.size; //size in kb fileSize = fileSize / 1048576; //size in mb } //for FF, Safari, Opeara and Others else { fileSize = $("#" + fileid)[0].files[0].size //size in kb fileSize = fileSize / 1048576; //size in mb } alert("Uploaded File Size is" + fileSize + "MB"); } catch (e) { alert("Error is :" + e); } } </script> </head> <body> <form name="upload" action=""> <input type="file" name="fUpload" id="fUpload" /> <input type="button" value="Get File Size" onclick="GetFileSize('fUpload');" /> </form> </body> </html>
Read More - jQuery Interview Questions for Experienced
Example to get file size before upload in Asp.Net using JQuery
Using above defined function "GetFileSize", we can also get file size in Asp.net also like as :
<form id="form1" runat="server"> <asp:FileUpload ID="fUpload" runat="server" /> <asp:Button ID="btnGetSize" runat="server" Text="Button" OnClientClick="GetFileSize('fUpload');" /> </form>
Above example will work on all browsers including IE, FF, Chrome, Safari, Opera etc.
Summary
In this article I try to expose how you can get size of file before uplaoding. I hope after reading this article you will be able to use this trick in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.