获取远程加载图像的url's文件大小

getting image url's file size of remotely loaded images

本文关键字:url 文件大小 图像 程加载 加载 获取      更新时间:2023-09-26

我在jQuery中有一个简单的regex函数,用于向用户发布的图像url添加图像标记。因此,当用户发布例如www.example.com/image.jpg的图像标签将被添加,以便用户可以看到图像,而无需点击URL。

var hostname = window.location.hostname.replace(/'./g,'''.');
var re = new RegExp('(http:''/''/[^' + hostname + ']''S+[''.jpeg|''.png|''.jpg|''.gif])','g');
$(".texthold ").each(function() {
    $(this).html($(this).html().replace(re, '<a href="$1"><img src="$1" /></a>')); 
});

我如何检查文件大小的图像之前允许它是可见的?例如,如果图像文件大小大于5MB,则不会显示图像,而是显示URL。

var url = ...; // here you build URL from regexp result
var req = $.ajax({
  type: "HEAD",
  url: url,
  success: function () {
    if(req.getResponseHeader("Content-Length") < 5 * 1048576) // less than 5 MB?
      ; // render image tag
    else
      ; // render URL as text   
  }
});

如果服务器对图像的响应包含适当的跨域资源共享(CORS)标头和内容长度的标头,您将能够完成您想要的。

此外,您还需要考虑在替换循环中完成ajax请求所需的时间。

下面是一个jQuery(1.9.1)示例,演示了最终的解决方案。要使其工作,您需要更新到服务器的链接,该服务器返回正确的CORS标头或禁用浏览器上的安全性。这个例子也在jsfiddle上。

var largeImage = "http://eoimages.gsfc.nasa.gov/images/imagerecords/49000/49684/rikuzentakata_ast_2011073_lrg.jpg";
var smallImage = "http://eoimages.gsfc.nasa.gov/images/imagerecords/81000/81258/kamchatka_amo_2013143_tn.jpg";
var urls = [largeImage, smallImage];
var maxSize = 5000000;
$.each(urls, function(index, value) {
    conditionalMarkupUpdater(value, maxSize);
});
var onShouldBeViewable = function () {
    alert('This is a small image...Display it.');
};
var onShouldNotBeViewable = function () {
    alert('This is a large image...Only provide the url.');
};
var onError = function() {
    alert('There was an error...likely because of CORS issues see http://stackoverflow.com/questions/3102819/chrome-disable-same-origin-policy and http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/"');
};
function checkSize(url) {
    var sizeChecker = new jQuery.Deferred();
    var onSuccess = function (data, textStatus, jqXHR) {
        var length = jqXHR.getResponseHeader('Content-Length');
        if (!length) {
            sizeChecker.reject("No size given");
        } else {
            sizeChecker.resolve(parseInt(length));
        }
    };
    var onFailure = function (jqXHR, textStatus, errorThrown) {
        sizeChecker.reject("Request failed");
    };
    $.when($.ajax({
        type: "HEAD",
        url: url
    })).then(onSuccess, onFailure);
    return sizeChecker.promise();
};
function conditionalMarkupUpdater(url, maxSize) {
    $.when(checkSize(url)).then(
    function (size) {
        if (size <= maxSize) {
            onShouldBeViewable();
        } else {
            onShouldNotBeViewable();
        }
    },
    function (status) {
        onError();
    })
};