Upload Base64 Image with Ajax

post sending base64 image with ajax

I finally managed to do it, The problem was located in the PHP file:

<?php
define('UPLOAD_DIR', 'images/');
// previously it was $img = $_POST['data']
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . 'test.png';
$success = file_put_contents($file, $data);
//send request to ocr
print $success ? $file : 'Unable to save the file.';
?>

From now, my saved image is exactly the one needed

How to post an image in base64 encoding via .ajax?

Thanks for all the answers which helped me along.

I had also posted the question to the forums on
https://social.msdn.microsoft.com/Forums/en-US/807ee18d-45e5-410b-a339-c8dcb3bfa25b/testing-project-oxford-ocr-how-to-use-a-local-file-in-base64-for-example?forum=mlapi (more Project Oxford specific) and between their answers and your's I've got a solution.

  1. You need to send a Blob
  2. You need to set the processData:false and contentType: 'application/octet-stream' options in the .ajax call

So my solution looks like this

First a function to make the blob (This is copied verbatim from someone more gifted than I)

makeblob = function (dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], { type: contentType });
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;

var uInt8Array = new Uint8Array(rawLength);

for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}

return new Blob([uInt8Array], { type: contentType });
}

and then

$.ajax({
url: 'https://api.projectoxford.ai/vision/v1/ocr?' + $.param(params),
type: 'POST',
processData: false,
contentType: 'application/octet-stream',
data: makeblob('data:image/jpeg;base64,9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z'
})
.done(function(data) {alert("success");})
.fail(function() {alert("error");});

Cant post base64 image on my post request with ajax

the method readAsDataURL is an asynchronous method. the return statement would make the function ends up before the reader finishes the extraction.

var getBase64 = function (file) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onloadend = function () {
base64String = reader.result;
resolve(reader.result);
};
reader.readAsDataURL(file);
})
}

var file = document.getElementById("imgid").files[0];
getBase64(file).then((base64String) => console.log(base64String) )

Save base64 image via AJAX to server

There are some issues with your code.

Wrong parameter

The first issue is that you post the data as imgBase64 but are trying to get it with $_POST['upload'].

Since you're not posting anything named upload, your if-statement: if (isset($_POST['upload'])) will always evaluate as false and your code inside the if will never be executed.

Use $_POST['imgBase64'] instead.

The base64 string

If you look at the beginning of the posted string, it probably starts with something like: data:image/jpeg;base64, (it's the js function toDataUrl() that adds that).

That is not part of the base64 encoded data so you need to remove that part from the string before trying to decode it.

It should be something like:

$str = str_replace('data:image/jpeg;base64,', '', $str);

You might need to change the string to replace to match what your string starts with.



Related Topics



Leave a reply



Submit