Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting image url's file size of remotely loaded images

I have a simple regex function in jQuery to add an image tag to image URLs posted by users. So that when a user posts for example www.example.com/image.jpg the image tag will be added so that user can see the image without clicking on the 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>')); 
});

How can I check the file size of the image before allowing it to be viewable? So that if for example the image file size is bigger than 5MB the image will not be displayed and instead the URL will be shown.

like image 619
ramr Avatar asked Jun 01 '13 20:06

ramr


2 Answers

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   
  }
});
like image 101
akhikhl Avatar answered Sep 24 '22 18:09

akhikhl


You will only be able to accomplish what you want if the server response for the images includes the appropriate Cross Origin Resource Sharing (CORS) header and a content-length header.

Additionally you will need to take into account the time required for the ajax requests to be fulfilled in your replacement loop.

Below is a jQuery (1.9.1) example which demonstrates what the final solution could look like. For it to work you will need to update the links to a server which returns proper CORS headers or disable security on your browser. The example is also on 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();
    })
};
like image 32
JesseHenn Avatar answered Sep 21 '22 18:09

JesseHenn