Using Jquery's Ajax Method to Retrieve Images as a Blob

Using jQuery's ajax method to retrieve images as a blob

You can't do this with jQuery ajax, but with native XMLHttpRequest.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is what you're looking for
handler(this.response);
console.log(this.response, typeof 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();

EDIT

So revisiting this topic, it seems it is indeed possible to do this with jQuery 3

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(){                    }    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script><img id="img" width=100%>

How to retrieve image BLOB from formData of jquery ajax in php

please see my answer..

       $(document).ready(function () {

$('#btn_save').on('click', function () {
var image = $('#image-id').val();
var base64ImageContent = image.replace(/^data:image\/(png|jpg);base64,/, "");
var PaymentStatus = $("#PaymentStatus").val();
var formData = new FormData();
formData.append('image', base64ImageContent);
formData.append('PaymentStatus', PaymentStatus);

$.ajax({
data: formData,
url: "/login/advshop/add",
method: 'POST',
processData: false,
contentType: false,
success: function (result) {
alert("form submitted");
},
error: function (result) {
alert('error');
//alert(result);

}
});
});
})

In Controller.

    public function add() {

$data = base64_decode($_POST['image']);

file_put_contents('images/test.jpg', $data);
}

you can directly pass the Base64 image content via ajax using formData append.decode the base64 content and put it in file_put_contents() function.

JQuery get image data? Is this blob?

It took a while but I found a suitable solution here for a base64 encode the image. I can also send the data over HTTP to my server to reconstruct the image.

http://theshravan.net/blog/get-image-data-url-using-javascript/

  var image = new Image();

// create an empty canvas element
var canvas = document.createElement("canvas"),
canvasContext = canvas.getContext("2d");

image.onload = function () {

//Set canvas size is same as the picture
canvas.width = image.width;
canvas.height = image.height;

// draw image into canvas element
canvasContext.drawImage(image, 0, 0, image.width, image.height);

// get canvas contents as a data URL (returns png format by default)
var dataURL = canvas.toDataURL();

//document.write(dataURL);
console.log(dataURL);
};

image.src = "image.png";

How to display BLOB image from MySQL through AJAX?

You cannot embed binary data into JSON because it will be damaged. This is why your server should encode the image to Base64 before sending it to the client. As a bad but simple example: if you are using MySQL 5.6+ you can add TO_BASE64(image) AS b64_image to your SELECT statement. But for better performance, encode images to Base64 using PHP, not MySQL.

Also, you need to fix your JavaScript code, by replacing:

"<td>"+"<img src='data:image/jpeg;base64', value="+value['image']+">"+"</td>";

with:

"<td><img src='data:image/jpeg;base64',"+value['b64_image']+"></td>";

Upload blob with AJAX and move file in the server

You should not use base64 for file upload. With a large file, your base64 will be extremely large. Although base64 is a relatively efficient way of encoding binary data it will, on average still increase the file size by more than 25%. This increases your bandwidth bill and uploads time. Instead, use the form data to upload the file. Just use base64 to preview the file before upload.

You also don't need to implement an XMLHttpRequest yourself (unless you want your code to work in IE :D) use Fetch API instead.

  <input id="file-upload" type="file" name="file" onchange="readFile()" /> 
<button id="upload-button" onclick="uploadFile()"> Upload </button>
<script>

function readFile() {

if(this.files && this.files[0]) {

const fileReader = new FileReader();

fileReader.addEventListener("load", function(e) {
//you can use base64 to preview file
console.log('Base64:', e.target.result);
});

fileReader.readAsDataURL( this.files[0] );
}

}

function uploadFile() {
const formData = new FormData();
const fileUploadInput = document.getElementById('file-upload');
formData.append("file", fileUploadInput.files[0]);

fetch('/upload.php', {
method: "POST",
body: formData
})
.then(() => {
console.log('Success');
})
.catch(error => {
console.error('Error:', error);
});
}
</script>

In PHP code, you can get the file from a global variable $_FILES

<?php
// upload.php
var_dump($_FILES['file']);
?>


Related Topics



Leave a reply



Submit