ASP.NET - Getting the file size in Javascript - Asked By Naresh Kumar on 08-Mar-11 01:12 AM

Hi All,

Is there any way to get the file size in javascript during file upload with out using any activeXControls.

Please advise.
Ritu Rani replied to Naresh Kumar on 08-Mar-11 01:18 AM
Hi Naresh,
you can use this function to get file size
<html>
<head>
<script>
function getSize()
{
	var myFSO = new ActiveXObject("Scripting.FileSystemObject");
	var filepath = document.upload.file.value;
	var thefile = myFSO.getFile(filepath);
	var size = thefile.size;
	alert(size + " bytes");
}
</script>
</head>
<body>
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onClick="getSize();">
</form>
</body>
</html>

use this hope this helps..............
Naresh Kumar replied to Ritu Rani on 08-Mar-11 01:24 AM
Thanks for your reply,

I want to get the file size with out using ActiveXObject.

please advise.
Anoop S replied to Naresh Kumar on 08-Mar-11 01:53 AM
The only way that you could do that is by use of an ActiveX object. Also note that ActiveX objects must be installed with the proper permissions on EVERY client.

please observe the below code
function validateFile()
{
var strFileName = document.form1.file1.value;
var strExtName = strFileName.substring(strFileName.lastIndexOf('.')).toLowerCase();
alert(strFileName);
alert(strExtName);
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var e = objFSO.getFile(strFileName);
var fileSize = e.size;
//file size limit for 10mb
if (fileSize > 10485760)
{
alert("maximum size of uploaded file should be less than 10 MB.");
return false;
}
 
else
return true;
 
}
 
<input type ="file" id="file1" name="file1" contentEditable="false" onchange="validateFile();" />


Otherwise you do Server side filter action
refer
http://aspalliance.com/1614_Adding_Filter_Action_to_FileUpload_Control_of_ASPNET_20.all
Reena Jain replied to Naresh Kumar on 08-Mar-11 01:53 AM
hi,

To get the size of a file hosted on the server, you could simply make an HEAD HTTP Request using Ajax. This kind of request is used to obtain metainformation about the url implied by the request without transferring any content of it in the response.

At the end of the HTTP Request, we have access to the response HTTP Headers, including the Content-Length which represents the size of the file in bytes.
A basic example using raw XHR:
var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'img/test.jpg', true);
xhr.onreadystatechange = function(){
  if ( xhr.readyState == 4 ) {
  if ( xhr.status == 200 ) {
    alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length'));
  } else {
    alert('ERROR');
  }
  }
};
xhr.send(null);

hope this will help you