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

How to Retrieve Images as Blobs Using jQuery's AJAX Method?

Barbara Streisand
Release: 2024-11-12 13:36:02
Original
213 people have browsed it

How to Retrieve Images as Blobs Using jQuery's AJAX Method?

Retrieve Images as Blobs Using jQuery's AJAX Method

Retrieving images as blobs using jQuery's AJAX method is not directly supported, as the accepted data types do not include image formats. This mismatch often results in corrupt images.

To overcome this limitation, you can utilize native XMLHttpRequest instead of jQuery's AJAX method. This approach allows you to explicitly set the responseType to 'blob':

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    handler(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

Alternatively, with jQuery version 3, it becomes possible to retrieve images as blobs:

jQuery.ajax({
  url: 'https://images.unsplash.com/...',
  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() {}
});
Copy after login

Utilizing this approach, you can efficiently retrieve images as blobs and subsequently perform operations such as uploading them to another server in a POST request.

The above is the detailed content of How to Retrieve Images as Blobs Using 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