一直以來我都覺得前端只能讀取圖片的寬度和高度,以及本地上傳圖片的大小(經過FileReader),但不能獲取到遠程圖片的大小。javascript
昨天在搜索時忽然意識到,http headers中包含Content-Length
參數,這不就是大小嗎?!而後立馬在console輸入$.get(src, function(data, statusText, res){res.getAllResponseHeaders()})
,這不就搞定了嘛!html
可是我高興太早了:expressionless: 把這個放在代碼裏,愣是不顯示Content-Length
!前端
而後繼續分析輸出,嘿嘿,data不就是圖片嗎?其長度不就是圖片原始大小嗎?!html5
是的,事情就是這個樣子的:triumph:代碼以下:java
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
的解讀:git
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
可獲取文件大小。github
補3:偶然發現一個不須要new Image
獲取圖片尺寸的思路,參考Marijn Haverbeke在Beautiful Javascript中的示例。不過該實現只支持部分PNG圖片。ajax