Home > Article > Web Front-end > 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();
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() {} });
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!