Reputation: 15
I want to get the file size of an image with jQuery.
Its almost there but i seem to keep on getting an error on one line Can anyone help me out :)
This is the full script that does all the magic. Heres a jsfiddle of it
function displayVals() {
var original = jQuery("#single").val();
jQuery(".origimg").attr("src", original);
var width = jQuery(".origimg").width();
jQuery(".origprev").attr("style", "background: url(" + original + ") no-repeat 0 0 / 100% auto transparent");
jQuery("p").delay(2000).queue(function() {
jQuery(this).html("http://src.sencha.io/" + width + "/" + original);
jQuery(".theimg").attr("src", "http://src.sencha.io/" + width + "/" + original);
function getImageSizeInBytes(original) {
var request = new XMLHttpRequest();
request.open("HEAD", original, false);
request.send(null);
var headerText = request.getAllResponseHeaders();
var re = /Content\-Length\s*:\s*(\d+)/i;
re.exec(headerText);
return parseInt(RegExp.$1);
}
var size_image = getImageSizeInBytes(original);
jQuery('.size').html(size_image);
})
}
jQuery('.go').click(
function() {
displayVals();
var original = jQuery("#single").val();
});
Upvotes: 1
Views: 1400
Reputation: 17094
The same origin policy doesn't allow resources to be requested from a domain different than the one making the request. For e.g., a script located on jsfiddle.net cannot 'XMLHttpRequest
' a resource located on src.sencha.io. Cross Origin Resource Sharing (CORS) allows for accessing resources located on different domains if the server sends this header: Access-Control-Allow-Origin: your-domain.com
In your JSFiddle demo, requesting for http://fiddle.jshell.net/favicon.png or /favicon.png works. This is because fiddle.jshell.net allows CORS for jsfiddle.net.
Try requesting with any other URL and look at your console. It should report: Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
Upvotes: 1