Home > Web Front-end > JS Tutorial > How to Retrieve Images as Blobs with jQuery's ajax Method?

How to Retrieve Images as Blobs with jQuery's ajax Method?

Barbara Streisand
Release: 2024-11-11 08:53:02
Original
809 people have browsed it

How to Retrieve Images as Blobs with jQuery's ajax Method?

Retrieving Images as Blobs with jQuery's ajax Method

Challenge

Retrieving images as blobs is not natively supported by jQuery's ajax method, leading to data type mismatches and corrupted images during upload.

Solution: Native XMLHttpRequest

To retrieve an image as a blob, utilize native XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        // this.response contains the blob
        handler(this.response);
    }
};
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();
Copy after login

jQuery 3.0 Support

Nowadays, it's possible to retrieve blobs with jQuery 3.0:

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() {
        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() {
        // Handle error
    }
});
Copy after login

The above is the detailed content of How to Retrieve Images as Blobs with jQuery's ajax Method?. 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