Find size of file behind download link with jQuery

旧时模样 提交于 2019-11-26 15:19:50

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"));
    }
  });
Sekar Ramamurthy

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>

If you know the file size beforehand, you can put that in the title attribute of the download link. You can also use jQuery to show a custom popup.

Otherwise, there is no way to get just the file size (content-length) of a URL without actually downloading the whole content AFAIK.

The only way that I can think of to do this would be to create a web service that would return you the filesize of the PDF.

In the answer above, Chrome 21 and Safari 6 did not have a fileSize member, but does have size. Use:

fileInput.files[0].size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!