Is it really possible?

Javscript is a pure client side scripting and if you ask me whether we can get the image size only by using javascript, than my answer is “NO”. Even if you run the files locally, you won’t be able to get the file size. But thankfully we run our websites from server and that why using a javascript AJAX trick you can get the size of the image or any other files. You can view the demo and also can download the source, but keep in mind the source files won’t work from local. You must upload them to any server, or you can install some freeware like ‘wamp’ and run these files from there. The demo and download links are given at the end of this article.

Why it is not possible from local?

Here I’m using ajax by javascript and sending an extra http request behind the scene by ‘XMLHttpRequest’. So there must be some server who can receive this request, process it and send back the required data. If you run the index file from local, then there will be no server to response on this request, that’s why this won’t work from local.

The code and explanation:

var obj = new XMLHttpRequest();'HEAD', '', true);
obj.onreadystatechange = function(){
  if ( obj.readyState == 4 ) {
    if ( obj.status == 200 ) {
      alert('Size in bytes: ' + obj.getResponseHeader('Content-Length'));
    } else {

Here I’m creating an XMLHttpRequest object and sending a header request with the respective file location (with extension). After that I’m triggering a function each time the ready state of my XMLHttpRequest object is changed. When the request is finished and the response is ready at that time the ready state is changed to 4. That’s why I’ve set a condition, that if readyState==4, that means if the response is ready. After that I’m checking whether the status is 200 or not. 200 means OK, and 404 means not found. So, if the status is 200 then i’m going to receive the response data. Content-Length is nothing but the file size.

Little more about XMLHttpRequest:

XMLHttpRequest is an web development API available in some scripting languages like javascript. This is basically used to send http or https request to a server behind the scene and load the response back to the script. This is supported by modern browsers, the older ones used to have a similar one called ActiveXObject. The onReadyStateChange event has its 5 ready stages. 0=request not initialized, 1=server connection established, 2=request received, 3=processing request, 4=processing finished and response is ready.

live-demo-button download-button