一直以来我都以为前端只能读取图片的宽度和高度,以及本地上传图片的大小(通过FileReader),但不能获取到远程图片的大小。
昨天在搜索时突然意识到,http headers中包含Content-Length
参数,这不就是大小吗?!然后立马在console输入$.get(src, function(data, statusText, res){res.getAllResponseHeaders()})
,这不就搞定了嘛!
但是我高兴太早了:expressionless: 把这个放在代码里,愣是不显示Content-Length
!
然后继续分析输出,嘿嘿,data不就是图片吗?其长度不就是图片原始大小吗?!
是的,事情就是这个样子的:triumph:代码如下:
var img = new Image();
img.onload = function() { // 先获取长度和宽度(像素)
$.ajax({ // 再获取图片大小(kb)
url: src,
type: 'GET',
complete: function(xhr, statusText) {
console.log(img.width, img.height, xhr.status === 200 ? (xhr.responseText.length/1024).toFixed(2) : 0);
}
});
};
img.src = src;
补:getResponseHeader()
不能获取content-length
的解读:
The XMLHttpRequest 2 object has a getResponseHeader() method that returns the value of a particular response header. During a CORS request, the getResponseHeader() method can only access simple response headers. Simple response headers are defined as follows:
- Cache-Control
- Content-Language
- Content-Type
- Expires
- Last-Modified
- Pragma
If you want clients to be able to access other headers, you have to use the Access-Control-Expose-Headers header. The value of this header is a comma-delimited list of response headers you want to expose to the client.
补2:如果是通过input[type="file"]
上传的文件,直接读取file.size
可获取文件大小。
补3:偶然发现一个不需要new Image
获取图片尺寸的思路,参考Marijn Haverbeke在Beautiful Javascript中的示例。不过该实现只支持部分PNG图片。
http://my.oschina.net/u/2324376/blog/416890