"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Retrieve Images as Blobs Using jQuery and JavaScript?

How to Retrieve Images as Blobs Using jQuery and JavaScript?

Posted on 2025-03-23
Browse:607

How to Retrieve Images as Blobs Using jQuery and JavaScript?

Retrieving Images as Blobs Using jQuery

In a previous question, you attempted to submit image data in a POST request. Your current approach involves using jQuery.ajax to retrieve the image, but you are encountering corrupt images due to data type mismatches.

Limited jQuery Data Types

jQuery.ajax supports several data types but does not explicitly include images. Therefore, accessing an image as a blob using jQuery alone is not feasible.

Native XMLHttpRequest Solution

To resolve this issue, you can employ native XMLHttpRequest. Here's an example:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var img = document.getElementById('img');
        var url = window.URL || window.webkitURL;
        img.src = url.createObjectURL(this.response);
    }
}
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();

This script will create an XMLHttpRequest object, configure it to receive a blob response, and use the Blob URL property to display the image in an HTML element.

jQuery 3 Solution

In jQuery 3, a new approach is available:

jQuery.ajax({
        url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ==&s=471ae675a6140db97fea32b55781479e',
        cache:false,
        xhr:function(){// Seems like the only way to get access to the xhr object
            var xhr = new XMLHttpRequest();
            xhr.responseType= 'blob'
            return xhr;
        },
        success: function(data){
            var img = document.getElementById('img');
            var url = window.URL || window.webkitURL;
            img.src = url.createObjectURL(data);
        },
        error:function(){
            
        }
    });

In this example, the xhr function is used to configure the XMLHttpRequest object, and the responseType is explicitly set to 'blob'. This allows jQuery to retrieve the image as a blob and display it in the image element.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3