14

Here's what I'm hoping to do:

I want to send an ajax request to a file (preferably with jQuery), and once the file has been loaded, determine the size of the requested file.

After a bit of googling, it's clear that I don't even have a good idea of the right question to ask to figure this out. Any help would be greatly appreciated.

3 Answers 3

41

You could make a HTTP HEAD request, and get a file size approximate by reading the Content-Length HTTP Header.

This kind of request is used to obtain meta-information about the URL implied by the request, without transferring any content of it in the response.

var xhr = $.ajax({ type: "HEAD", url: "path/to/file.ext", success: function(msg){ alert(xhr.getResponseHeader('Content-Length') + ' bytes'); } }); 
Sign up to request clarification or add additional context in comments.

2 Comments

I agree - I actually may end up using the other method for cross domain functionality, but this is really the answer I was looking for when I asked.
What about over HTTPS?
3

You could create a server-side command that takes the path and name of the file, opens the file to get the length, and sends the size back to the client. How you do it would depend on what server-side language you're using. Is that the type of action you're looking for?

3 Comments

Hm... So, I could use ajax to call a php file, which would load up the contents of the file I actually want, figure out how big it is, then return both the file contents and the size to javascript. And doing it that way would allow me to call content from another domain without trouble. That sounds absolutely brilliant - not at all what I thought I was looking for, but a fantastic solution.
Yeah, I have done that in the past with Java when creating an authorized download controller. You might also want to look at CMS's suggestion -- I've never thought of using the HEAD command, but if all you need is file size, that might work even more brilliantly.
this is the only answer so far that avoids gzip encoding causing content-length not to be sent back.
0
var XHRObj = $.ajax({ type:'HEAD', url:'/', success:function(data) { console.log( XHRObj.getResponseHeader('Content-Length') ) } }) 

You basically do a HEAD HTTP request and query the Content-Length, which returns X bytes.

1 Comment

if gzip encoding is used the content-length header doesn't get sent

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.