Home > Web Front-end > JS Tutorial > Why can't you use jQuery.ajax to retrieve images as blobs?

Why can't you use jQuery.ajax to retrieve images as blobs?

Mary-Kate Olsen
Release: 2024-11-13 03:58:01
Original
929 people have browsed it

Why can't you use jQuery.ajax to retrieve images as blobs?

Using XMLHttpRequest to Retrieve Images as Blobs

You are attempting to retrieve an image using jQuery.get, store it in a Blob, and upload it to another server. However, the mismatch in data types is causing the images to become corrupt.

Why can't you use jQuery ajax to retrieve images as blobs?

jQuery.ajax does not support retrieving images as blobs.

Solution

To retrieve an image as a blob, you need to use native XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200){
        //this.response is what you're looking for
        handler(this.response);
        console.log(this.response, typeof this.response);
        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();      
Copy after login

Update for jQuery 3

As of jQuery 3, it is possible to retrieve images as blobs using jQuery.ajax:

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%3D%3D&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(){
            
        }
    });
Copy after login

The above is the detailed content of Why can't you use jQuery.ajax to retrieve images as blobs?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template