I want to parse the requested image from my REST API into base64 string.
Firstly... I thought, it would be easy, just to use window.btoa()
function for this aim.
When I try to do it in such part of my application:
.done( function( response, position ) {
var texture = new Image();
texture.src = "data:image/png;base64," + window.btoa( response );
I've got the next error: Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
As I read here: javascript atob returning 'String contains an invalid character'
The issue occurs because of newlines in the response
and that's why window.btoa()
failed.
Any binary image format of course will have newlines... But as from the link above the suggestion was to remove/replace those characters - is a bad suggestion for me, because if to remove/replace some characters from binary image it just will be corrupted.
Of course, the possible alternatives relate to the API design: - to add some function, which return base64 representation - to add some function, which return url to the image
If I won't repair it, I shall return base64 representation from the server, but I don't like such a way.
Does exist some way to solve my problem with the handling binary image from response, as it's shown above in the part of screenshot, doesn't it?
Base 64 Image data is worked for me like
<img src="data:image/png;base64,' + responce + '" />
Im guessing to use
escape
on the string before you pass it to the function, without the API call I can't test myself.test
returns
It just escapes all the characters, it should escape all the illegal characters in the string
test
returns
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
instead of looping through the blob with _arrayBufferToBase64(), use apply() to do the conversion, it's 30 times faster in my browser and is more concise
The issue you're encountering is that the response is being considered a Unicode String. See the section on Unicode Strings here: window.btoa
Several solutions are offered in this post
I think part of the problem you're hitting is that
jQuery.ajax
does not natively support XHR2 blob/arraybuffer types which can nicely handle binary data (see Reading binary files using jQuery.ajax).If you use a native XHR object with
xhr.responseType = 'arraybuffer'
, then read the response array and convert it to Base64, you'll get what you want.Here's a solution that works for me:
https://jsfiddle.net/oy1pk8r3/2/
Produces base64 encoded console output:
/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAIBAQIBAQICAgICAgICAw.....