Home >Web Front-end >JS Tutorial >How to Retrieve Images as Blobs Using jQuery and JavaScript?
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%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(){ } });
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.
The above is the detailed content of How to Retrieve Images as Blobs Using jQuery and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!