I have some javascript code that uploads an image to a server. Below is the ajax call that works correctly.
$.ajax({
url: 'https://api.projectoxford.ai/vision/v1/analyses?',
type: 'POST',
contentType: 'application/json',
data: '{ "Url": "http://images.takungpao.com/2012/1115/20121115073901672.jpg" }',
})
I now need to upload the image a a base64 encoding e.g.
data: 'data:image/jpeg;base64,/9j/4AAQSkZJRgA..........gAooooAKKKKACiiigD//Z'
But that doesn't work, i.e. the server doesn't recognise the data I send and complains.
Does anyone know what the correct format is for sending base64 encoded data in the AJAX call ?
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.
processData:false
and contentType: 'application/octet-stream'
options in the .ajax callSo 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");});
This is some working code from my own application. You will need to change the contentType
and data
args in your ajax operations.
var video = that.vars.video;
var code = document.createElement("canvas");
code.getContext('2d').drawImage(video, 0, 0, code.width, code.height);
var img = document.createElement("img");
img.src = code.toDataURL();
$.ajax({
url: '/scan/submit',
type: 'POST',
data: { data: code.toDataURL(), userid: userid },
success: function (data) {
if (data.error) {
alert(data.error);
return;
}
// do something here.
},
error : function (r, s, e) {
alert("Unexpected error:" + e);
console.log(r);
console.log(s);
console.log(e);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With