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();
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 } });
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!