6

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.

dirkk
  • 6,160
  • 5
  • 33
  • 51
ramr
  • 1,019
  • 1
  • 10
  • 17
  • This can be done easily with PHP see -http://stackoverflow.com/questions/4635936/super-fast-getimagesize-in-php – ramr Jun 01 '13 at 20:15
  • Any answers in jquery or javascript would be much appreciated i guess! – ramr Jun 01 '13 at 20:16
  • 2
    Possible duplicate: http://stackoverflow.com/questions/1484303/get-size-of-file-requested-via-ajax – lightbricko Jun 01 '13 at 21:36
  • You could do a `HEAD` (as opposed to `GET` or `POST`) on the URL and check the `Content-Length` header. **Edit:** after looking at the above link from @lightbricko I see that was the suggestion there complete with code... ;) – Shadow Man Jun 01 '13 at 21:41

2 Answers2

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   
  }
});
akhikhl
  • 2,552
  • 18
  • 23
1

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();
    })
};
JesseHenn
  • 73
  • 6