开发者

Detect the file size of a link's href using JavaScript

Would like to write a script to detect the file size of the target of a link on a web page.

Righ开发者_C百科t now I have a function that finds all links to PDF files (i.e. the href ends with '.pdf') and appends the string '[pdf]' to the innerText. I would like to extend it so that I can also append some text advising the user that the target is a large file (e.g. greater than 1MB).

Thanks


Some web servers may give you a Content-Length header in response to a HEAD request. You could potentially use an XmlHttpRequest to send the HEAD request and see what you get.

Here's what one of my IIS servers says about a PDF file:

HTTP/1.1 200 OK
Content-Length: 127791
Content-Type: application/pdf
...

However, anything that's not delivered directly by the web server (a file served by PHP or ASP.net, for example) won't work unless the script specifically handles HEAD requests.


You should be able to do a HEAD request using XMLHttpRequest, assuming the files are under the same domain.

This is however something that should really be done on the server side. Doing it with extra requests has no benefit whatsoever.


You can't do this, or at least - not in any practical-cross-browser way.

If you know the filesize beforehand, for example when generating the document linking to the files you could hard-code the sizes into the HTML document.

<a href="large_file.pdf" onclick="return confirm('Want to download a large file?')">large_file.pdf</a>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜