Find size of file behind download link with jQuery
I was wondering if there was a way to use jQuery to find out the file size for a PDF that i'm linking to a webpage.
I want to make it so that on hovering over the download link, a modal box pops up saying the file size of the PDF. I can do the second bit, the only thing i'd like to know is how to find out the file size. I dont know if jQuery is capable of this. If not then too bad i guess..
Cheers in advance.
I feel like this is too much to be doing client-side, but I don't know the details of your application, so presuming you have to do it with jQuery... you can do a HEAD request and look at the Content-Length header. Earlier I recommended the jqHead plugin, but after I tried to use it I found that it was broken.
Here's a working example that doesn't depend on any extra plugins: http://host.masto.com/~chris/so/jqhead.html
The meat of it is very simple:
var request;
request = $.ajax({
type: "HEAD",
url: $("#url").val(),
success: function () {
alert("Size is " + request.getResponseHeader("Content-Length"));
}
});
Here is working snippet to find the file size in javascript without going to the server, if you are about to upload the file to the server.
This idea helps to restrict the file size before uploading big files to the server.
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="findSize()" />
<script type="text/javascript">
function findSize() {
var fileInput = $("#loadfile")[0];
alert(fileInput.files[0].size); // Size returned in bytes.
}
</script>