Javascript string encoding Windows-1250 to UTF8 - javascript

I've an angularjs app that receive data from an external webservice.
I think I'm receiving UTF-8 string but encoded in ANSI.
For example I get
KLMÄšLENÃ
When I want to display
KLMĚLENÍ
I've tried to use decodeURIComponent to convert it but that doesn't work.
var myString = "KLMÄšLENÃ"
console.log(decodeURIComponent(myString))
I'm probably missing something but I can't find what.
Thanks and regards,
Eric

You can use TextDecoder. (Be beware! some browser does not support it.)
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
if (this.status == 200) {
var dataView = new DataView(this.response);
var decoder = new TextDecoder("utf-8");
var decodedString = decoder.decode(dataView);
console.log(decodedString);
} else {
console.error('Error while requesting', url, this);
}
};
xhr.send();
Java servlet code for simulating server side output:
resp.setContentType("text/plain; charset=ISO-8859-1");
OutputStream os = resp.getOutputStream();
os.write("KLMĚLENÍ".getBytes("UTF-8"));
os.close();

Related

How to pass base64encode string through XMLHttpRequest() post request

I am trying to upload a image to server,In that i have converted image to base64encode string and i need to pass that base64encode string to webservice,that webservice convert the base64 string to file and saving in database.but base64encode string has huge length approximately(85,000) when i pass this string to webservice i am getting the following error.
Failed to load resource: the server responded with a status of 400 (Bad Request)
i need to pass this by using only XMLHttpRequest() with out using the ajax,jquery please help me.
below is my code.
var filesToBeUploaded = document.getElementById("afile");
var file = filesToBeUploaded.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var binaryStringResult = reader.result;
var binaryString =binaryStringResult.split(',')[1];
var xhr = new XMLHttpRequest();
xhr.open("POST","http://url/api/jsonws/Global-portlet.org_roles/add-file-entry?repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString);
xhr.setRequestHeader("Authorization","BasicbmFyYXlhbmFAdmlkeWF5dWcuY29tOnRlc3Q=");
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send();
xhr.onload = function() {
alert('in sucess');
};
xhr.onerror = function(e) {
alert('in error');
};
}
reader.readAsDataURL(file);
For POST, don't include it in the URL, you need to put it in the body, i.e.
xhr.send(binaryString);
I doubt your Content-Type of application/x-www-form-urlencoded is correct in this case.
I think the issue that you encountering here is that you are exceeding the maximum length of a query string.
What you need to do is something like the following:
var xhr = new XMLHttpRequest();
var url = "http://url/api/jsonws/Global-portlet.org_roles/add-file-entry";
var params = "repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(params);
Hope that helps

XMLHttpRequest returns wrongly encoded characters

I use XMLHttpRequest to read the PDF document
http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf
%PDF-1.3
%âãÏÓ
[...]
and print its content out to console:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
console.log('âãÏÓ');
}
};
xhr.open('GET', 'http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf', true);
xhr.send();
However, the console says
%PDF-1.3
%����
[...]
âãÏÓ
(The last line is from the reference console.log above to verify that the console can actually display those characters.)
Apparently, the characters are wrongly encoded at some point. What's going wrong and how to fix this?
XMLHttpRequest's default response type is text, but here one is actually dealing with binary data. Eric Bidelman describes how to work with it.
The solution to the problem is to read the data as a Blob, then to extract the data from the blob and plug it into hash.update(..., 'binary'):
var xhr = new XMLHttpRequest();
xhr.open('GET', details.url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status === 200) {
var a = new FileReader();
a.readAsBinaryString(this.response);
a.onloadend = function() {
var hash = crypto.createHash('sha1');
hash.update(a.result, 'binary');
console.log(hash.digest('hex'));
};
}
};
xhr.send(null);
The MIME type of your file might not be UTF-8. Try overriding it as suggested here and depicted below:
xhr.open('GET', 'http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf', true);
xhr.overrideMimeType('text/xml; charset=iso-8859-1');
xhr.send();

How to parse into base64 string the binary image from response?

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?
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:
// http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
function fetchBlob(uri, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', uri, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
if (callback) {
callback(blob);
}
}
};
xhr.send();
};
fetchBlob('https://i.imgur.com/uUGeiSFb.jpg', function(blob) {
// Array buffer to Base64:
var str = btoa(String.fromCharCode.apply(null, new Uint8Array(blob)));
console.log(str);
// Or: '<img src="data:image/jpeg;base64,' + str + '">'
});
https://jsfiddle.net/oy1pk8r3/2/
Produces base64 encoded console output: /9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAIBAQIBAQICAgICAgICAw.....
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
// http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
function fetchBlob(uri, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', uri, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
if (callback) {
callback(blob);
}
}
};
xhr.send();
};
fetchBlob('https://i.imgur.com/uUGeiSFb.jpg', function(blob) {
var str = String.fromCharCode.apply(null, new Uint8Array(blob));
console.log(str);
// the base64 data: image is then
// '<img src="data:image/jpeg;base64,' + btoa(str) + '" />'
});
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
encodeURI("testñ$☺PNW¢=")
returns
"test%C3%B1$%E2%98%BAPNW%C2%A2="
It just escapes all the characters, it should escape all the illegal characters in the string
test
encodeURI("¶!┼Æê‼_ðÄÄ┘Ì+\+,o▬MBc§yþó÷ö")
returns
"%C2%B6!%E2%94%BC%C3%86%C3%AA%E2%80%BC_%C3%B0%C3%84%C3%84%E2%94%98%C3%8C++,o%E2%96%ACMBc%C2%A7y%C3%BE%C3%B3%C3%B7%C3%B6"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
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
Try this on its working well. please try once. #user2402179
$.ajax({
type: 'GET',
url: baseUrl",
dataType: 'binary',
xhr() {
let myXhr = jQuery.ajaxSettings.xhr();
myXhr.responseType = 'blob';
return myXhr;
},
headers: {'Authorization': 'Bearer '+token}
}).then((response) => {
// response is a Blob
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.addEventListener('load', () => {
$('#theDiv').append('<img src="' +reader.result+ '" />')
resolve(reader.result);
}, false);
reader.addEventListener('error', () => {
reject(reader.error);
}, false);
reader.readAsDataURL(response);
});
});
Base 64 Image data is worked for me like
<img src="data:image/png;base64,' + responce + '" />

JavaScript - how to view raw data for an image

Is it possible to view the raw data for an image file in javascript?
I'm trying to write a script that converts an image into its hex dump.
How can I view the data I'm writing to the image file?
You can do this with XHR:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/my/image/file.png', true);
xhr.responseType = 'arraybuffer'; // this will accept the response as an ArrayBuffer
xhr.onload = function(buffer) {
var words = new Uint32Array(buffer),
hex = '';
for (var i = 0; i < words.length; i++) {
hex += words.get(i).toString(16); // this will convert it to a 4byte hex string
}
console.log(hex);
};
xhr.send();
Look at the doc for ArrayBuffers and TypedArrays
And you can see how I use it in testing here
Is it possible to get the source code of a file in javascript?
Find the URL for the script and load that into your browser. (Or use Firebug)

fetch filepicker file into arraybuffer in web browser

I'm trying to use filepicker.io to fetch binary data and pass it into a function like this:
var doSomething = function(arrayBuffer) {
var u16 = new Int16Array(arrayBuffer);
}
I have no idea how to convert the binary into arraybuffer like this:
filepicker.getContents(url, function(data){
//convert data into arraybuffer
}
I tried to follow this tutorial on XMLHttpRequest but does't not work.
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
doSomething(this.response);
};
You are not calling .send with your XHR
xhr.send(null);

Categories