Javascript 无论如何使用javascript(或jquery之类的)获取图像文件大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3272441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
anyway to get image file size using javascript(or jquery like)
提问by Koerr
like:
喜欢:
<img src="http://www.google.com/intl/en_ALL/images/srpr/logo1w.png">
i want get logo1w.png file size 7.3kb
我想要 logo1w.png 文件大小 7.3kb
how to implement it?
如何实施?
采纳答案by bernedef
Check out this : Determining image file size + dimensions via Javascript?
回答by Manfre
You could do an HTTP HEAD request for the image URL. This will return the HTTP headers, which include the content-length (a.k.a. file size). This does require an additional request to the server, which is not very efficient when the image is generated instead of being served statically.
您可以对图像 URL 执行 HTTP HEAD 请求。这将返回 HTTP 标头,其中包括内容长度(又名文件大小)。这确实需要向服务器发出额外的请求,这在生成图像而不是静态提供时效率不高。
回答by Weston C
I don't know of any single way to consistently get the exactfile size, but if you're willing to jump through some hoops, you could:
我不知道有任何一种方法可以始终如一地获得确切的文件大小,但是如果您愿意跳过一些麻烦,您可以:
1) Estimate based on the dimensions and the file type. Because of compression techniques there's some wide variation, but you could probably run some statistics and come up with a half-decent heuristic.
1) 根据尺寸和文件类型估算。由于压缩技术存在一些广泛的变化,但您可能会运行一些统计数据并提出一个半体面的启发式方法。
2) In IE, use the fileSizeproperty of an image. In other browsers that support Canvas, use the technique described in this question on getting image data in JavaScriptto grab the dataURL, then do the math (multiply by 3/4, since base64 is a 4/3 size increase).
2) 在 IE 中,使用fileSize图像的属性。在支持 Canvas 的其他浏览器中,使用本问题中描述的技术在 JavaScript 中获取图像数据来获取 dataURL,然后进行数学运算(乘以 3/4,因为 base64 大小增加了 4/3)。
Edit
编辑
3) The suggestion others have given (particularly as elaborated in the question linked in Fabien Bernede's answer) about getting HTTP Headers is brilliant AND precise. Probably runs afoul of cross-domain restrictions in some cases, but still probably the most consistent and effective method.
3) 其他人给出的关于获取 HTTP 标头的建议(特别是在 Fabien Bernede 的回答中链接的问题中详细说明的)非常出色且精确。在某些情况下可能会违反跨域限制,但仍然可能是最一致和最有效的方法。
回答by redsquare
You cannot in javascript (sorry even magical jQuery cannot help here!). You would need a server side script to fetch the image for you and calculate the size which you could return to your page.
你不能在 javascript 中(抱歉,即使是神奇的 jQuery 在这里也帮不上忙!)。您需要一个服务器端脚本来为您获取图像并计算您可以返回到您的页面的大小。
Note - downvoters beware, the OP does not own the google domain!
注意 - 投票者要小心,OP 不拥有 google 域!
回答by GWolf
$fileSize = strlen(file_get_contents($imageSrcTag)) // <-- php
$fileSize = strlen(file_get_contents($imageSrcTag)) // <-- php

