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

时间:2013-06-01 20:10:10

标签: javascript jquery image image-processing remote-access

我在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。

2 个答案:

答案 0 :(得分:4)

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   
  }
});

答案 1 :(得分:1)

如果图像的服务器响应包含适当的跨源资源共享(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();
    })
};