decode base64 image fail after retrive from database - javascript

May it easy. But i can't figure it out.
I am using cordova camera plugin which give me direct base64 data like following..
navigator.camera.getPicture(onSuccess, onFail, {quality: 50,
destinationType: Camera.DestinationType.DATA_URL});
function onSuccess(imageData) {
$('#userFullProfileImage').attr('src', "data:image/jpeg;base64," + imageData);
}
It is working. Because it shows me the image after set source of userFullProfileImage. So encoding is correct.
Now, i am trying to save imageData in mysql and retrieve it via ajax.
After retrieve i match several line and found no mistake. imageData before save and imageData after retrieve seems to me same ( But save data omit all + character)
Retrieved image data can't decode. I use online base64 decoder too. But no hope. May be missing + character is for this reason.
I have checked all other character, line by line, both of imageData are same.
So now help me, which could be the possible reasons in my case.

If your + characters are being stripped, it sounds like it's going through a URL encoding scheme, which could convert + to spaces, which could then be ignored as whitespace by the base64 decoder. This could be happening as part of your AJAX request, which defaults to application/x-www-form-urlencoded.
If you say that you're going to submit url encoded data, then don't encode it, it will be incorrectly decoded by the server on receipt.
Try setting your content type in the AJAX request e.g.
$.post({
url: yourUrl,
data: JSON.stringify(yourBase64string),
contentType: "application/json",
dataType: "json"
});
Where contentType will tell the server that you're submitting your data as JSON and dataType will tell the server what format you expect the response to be in (so in this case the server should send its response in JSON, but you could also use a dataType of e.g. "text")
You could alternatively use a contentType of "text/plain" and remove the JSON.stringify but I have not tested this.

My problem was during send image data through ajax.
encodeURIComponent(imageData); //This solve my problem.
Encoded data is now safely save in database.
After retrieve from encoded data from database i have just used another function.
decodeURIComponent(encodedData); //same of imageData

Related

How to pass entire html img element with Base64String to server through ajax?

Hi i am trying to ajax save contents of Rich text editor as such(Raw HTML content) in database.I have other inputs values along with this editor value to be passed along in ajax call...
hence i construct a json String with all inputs value in my page and send it in ajax as request param
&1_Question={
SubRefNumber:"QuestionBank.js",
QuestionType:"Subjective",
Level:"-----",
QBType:"-----",
Question:"<p><img src=\\'data:image/jpeg;base64,/9j/4AAQSkZJRg..ICIiAiIg//Z\\' /></p>",
Hints:"null",
SubjectiveSolution:"QuestionBank.js"
}&QuestionsKeyList=1_Question
i face problem with the img tag passed in request. my problem is that the Rich editor(Tinymce)i use converts uploaded images to base64 src data, hence when i try to save that base64 string, it contents gets modified somehow when passing to server....
$.ajax({
url: saveUrl ,
type: 'POST',
data: dat ,
cache: false,
processData: false,
success: function(response){
}
});
the string saves in db without any issues but when i get the saved image to display again in page i get corrupted image... when i compared the base64 string sent from ajax and base64 string received in server before saving both were different !! some characters like '+' were missing when received # server side...Why is it so..Please Guide...

How to send big files using ajax?

So currently I'm working on a simple project where users gets to upload an image to server. Before I mention my problem here is how I'm doing it:
Client:
var dataURL = sendingcanvas.toDataURL("image/*");
var imagedatatosend = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
formdata = {
'image': imagedatatosend
};
$.ajax({
url: '../receive',
type: 'POST',
data: formdata,
encode: false,
success: function(result){
alert(result);
}
});
FYI: imagedatatosend size is lower than 5MB and contains exactly the file data selected.
Basically What happens Is that users select an image using <input type="file" tag Then I'm setting that selected file drawn in a canvas to convert it to base64 and send it to server.
Java Server:
String datareceived = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
byte[] bImg = Base64.decodeBase64(datareceived.getBytes("UTF-8"));
FileOutputStream fos = new FileOutputStream("hi.jpg");
fos.write(bImg);
fos.close();
I think I might not need to explain what the code above does. But I'm facing some serious performance problem I mean It takes some huge time to write the data to hi.jpg file, even if I try System.out.println(datareceived); It takes seconds for my mouse click to respond on server console.
I don't know why is it happening, Do I need to send the image data as multipart or what?
All replies are appreciated and Thanks in Advance:)
Use XMLHttpRequest and FormData to append the file. It will be sent using multipart and chunked appropriately.
See: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

Chrome extension ajax sending malformed accented characters

I am sending an AJAX POST request using jQuery on a chrome extension but the data doesn't arrive as expected, accented characters turn out malformed.
The text "HÄGERSTEN" becomes "HÄGERSTEN".
The text appears fine in the console etc, only via AJAX to this other page it appears as mentioned. My AJAX call is basic, I send a data-object via jQuery $.ajax. I've tried both with and without contentType, UTF-8 and ISO-8859-1. No difference.
This is how I make my AJAX call:
var newValues = {name: 'HÄGERSTEN'}
$.ajax({
url: POST_URL,
type: 'POST',
data: newValues,
success: function() ...
});
The newValues object has more values but I retrieve them from a form. However, I have tried to specify these values manually as newValues['name'] = 'ÄÄÄÄ'; and still would cause the same problem.
The original form element of the page that I am sending the AJAX to contains attribute accept-charset="iso-8859-1". Maybe this matters.
The target website is using Servlet/2.5 JSP/2.1. Just incase it might make a difference.
I assume this is an encoding issue and as I've understood it should be because Chrome extensions require the script files to be UTF-8 encoded which probably conflicts with the website the plugin is running on and the target AJAX page (same website) which is using an ISO-8859-1 encoding, however I have no idea how to deal with it. I have tried several methods of decoding/encoding it to and from UTF-8 to ISO-8859-1 and other tricks with no success.
I have tried using encodeURIComponent on my values which only makes them show that way exactly on the form that displays the values I have sent via POST, as e.g. H%C3%84GERSTEN.
I have no access to the websites server and cannot tell you whether this is a problem from their side, however I would not suppose so.
UPDATE
Now I have understood POST data must be sent as UTF-8! So a conversion is not the issue?
Seems like the data is UTF-8 encoded when it is sent and not properly decoded on the server side. It has to be decoded on the server side. Test it out with the following encode and decode functions:
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
var encoded_string = encode_utf8("HÄGERSTEN");
var decoded_string = decode_utf8(encoded_string);
document.getElementById("encoded").innerText = encoded_string;
document.getElementById("decoded").innerText = decoded_string;
<div>
Encoded string: <span id="encoded"></span>
</div>
<div>
Decoded string: <span id="decoded"></span>
</div>
We too faced the same situation but in our case we always sent the parameters using JSON.stringify.
For this you have to make changes, 1) While making call to the page via AJAX you have to add content-type tag defining in which encoding data is sent
$.ajax
({
type: "POST",
url: POST_URL,
dataType: 'json',//In our case the datatype is JSON
contentType: "application/json; charset=utf-8",
data: JSON.stringify(newValues),//I always use parameters to be sent in JSON format
EDIT
After reading your question more clearly I came to know that your server side JSP uses ISO-8859-1 encoding and reading some posts, I came to know that all POST method data will be transmitted using UTF-8 as mentioned.
POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard
But while reading post jquery-ignores-encoding-iso-8859-1 there was a workaround posted by iappwebdev which might be useful and help you,
$.ajax({
url: '...',
contentType: 'Content-type: text/plain; charset=iso-8859-1',
// This is the imporant part!!!
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
}
});
Above code is taken from Code Posted by iappwebdev
I don't know if it could have been solved using POST-data and AJAX. Perhaps if I made a pure JavaScript XHR AJAX call, I might be able to send POST-data encoded the way I like. I have no idea.
However, in my desperation I tried my final option (or what seemed like it); send the request as GET-data. I was lucky and the target page accepted GET-data.
Obviously the problem still persisted as I was sending data the same way, being UTF-8 encoded. So instead of sending the data as an object I parsed the data into a URL friendly string with my own function using escape, making sure they are ISO-8859-1 friendly (as encodeURIComponent encodes the URI as UTF-8 while escape encodes strings making them compatible with ISO-8859-1).
The simple function that cured my headaches:
function URLEncodeISO(values) {
var params = [];
for(var k in values) params[params.length] = escape(k) + '=' + escape(values[k]);
return params.join('&');
}
The client side character coding is not completely up to you (immagine the usage of the page from different users all around the world: chinese, italian...) while on the server side you need to handle the coding for your purposes.
So, the data in the Ajax-POST can continue to be UTF8-encoded, but in your server side you coan to do the following:
PHP:
$name = utf8_decode($_POST['name']);
JSP:
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");

How do I send image canvas data to Transloadit?

Transloadit appears to have only a Upload Form API. I wish to send the contents of my canvas to Transloadit like so:
data = canvas.toDataURL();
// POST this data to Transloadit
$.ajax({
type: 'POST',
url: 'http://api2.transloadit.com/assemblies',
// what goes here?
}).done(function() {
console.log('Done uploading!');
});
Is this possible?
It appears that Transloadit still does not support base64 data, but with newer browsers it's possible to take base64 data from a variable, convert it to binary, and send it in a file upload.
http://support.transloadit.com/discussions/questions/8587-how-to-upload-a-canvas-image-to-transloadit

Sending image data over AJAX from jquery

I need to send image data (data:image/png;base64) from the clientside using AJAX to my PHP server. My AJAX call looks like this:(form_data contains the image)
$.ajax({
url: global_siteurl+'/save_image',
data: form_data,
dataType: 'json',
type: 'post',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (retval) {
process_save_image(retval);
}
});
Then I store the encoded image data as a blob in the database (yes - long story behind that!). When I retrieve the image data it seems to be corrupted and does not display correctly. Almost as if there are line breaks and spaces introduced into the image data. Am I missing any parameters in my ajax call? Any ideas as to what may be going wrong? Is there a size limit for the image data I can send across?
It's been a long 4 days of chasing this one.
Mmiz
The problem turned out to be the same described (and solved) in this posting:
Blob data replace '+' with space
Turns out I needed to make the blob data safe for URLs when I GET/POST it. On the PHP server side I used the function described in the above posting. On the Javascript side, I used the functions from:
http://notepad2.blogspot.com/2012/08/javascript-make-base64-encoded-string.html
Took a lot of staring at the encoded image data to notice that the +/= were replaced.
Try this when showing image.
echo '<img src="data:image/png;base64,' . base64_encode($blob_data) . '"/>

Categories