FileReader::readAsArrayBuffer, how to get length? - javascript

I try to read file into array buffer. The file seems to read correctly but the length is 'undefined'?
var file_reader = new FileReader();
file_reader.onloadend = function (e) { parse_file.apply(null, [e.target.result]); };
var xhr = new XMLHttpRequest();
xhr.open('get', 'a_blob_file.dat');
xhr.responseType = 'blob';
xhr.onload = function(e) {
file_reader.readAsArrayBuffer(this.response);
}
xhr.send();
function parse_file(data)
{
console.log('length: ' + data.length); // <== undefined?
}

Related

How to return the result from XMLHttpRequest?

I have following function to convert local file to base64. When I run it, it writes the result (res) to console. How can I return the content of res from the function, so I can use it in another one?
function convertToBase64() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "1.jpg", true);
xhr.responseType = "blob";
xhr.onload = function (e) {
var reader = new FileReader();
reader.onload = function(event) {
var res = event.target.result;
console.log(res);
}
var file = this.response;
reader.readAsDataURL(file)
};
xhr.send()
}
(I am totally new in JavaScript.)
you can pass callback to your function to execute when file loaded
function convertToBase64(onLoad) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "1.jpg", true);
xhr.responseType = "blob";
xhr.onload = function (e) {
var reader = new FileReader();
reader.onload = function(event) {
var res = event.target.result;
console.log(res);
onLoad(res); // callback
}
var file = this.response;
reader.readAsDataURL(file)
};
xhr.send()
}
now you can do this :
convertToBase64(function(res) {
console.log('response loaded' , res);
});

How can I show the image my api returns in js/HTML?

I want to show a pdf file from a GET request on a HTML page using plain Java Script.
The api returns a pdf-file.
This is the postman response of the api:
Here is my code so far:
function getImg() {
var url = "https://api.herokuapp.com/download"
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", "JWT " + localStorage.getItem('token'));
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.send(null);
xhr.addEventListener('load', function() {
var responseObject = this.response;
var myImage = new Image();
myImage = this.response;
document.body.appendChild(myImage);
});
}
I get this error:
TypeError: Argument 1 of Node.appendChild is not an object.
How can this be done?
Any help is very appreciated.
BR KRESTEN
Here is how I solve this:
function getImg() {
var url = "https://secure.gravatar.com/avatar/3167fa1b890ffe735393de7d6296e32d?s=58&d=mm&r=g"
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
// xhr.setRequestHeader("Authorization", "JWT " + localStorage.getItem('token'));
// xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.send(null);
xhr.addEventListener('load', function() {
if (this.status === 200) {
let blob = this.response;
let myImage = new Image();
myImage.src = window.URL.createObjectURL(blob);
document.body.appendChild(myImage);
}
});
}

Why is my array buffer empty server-side?

I have a method in JavaScript to read from a binary file into an ArrayBuffer and send it to a Jersey POST method:
function readAndSendBytes() {
var file = document.getElementById("entityFileField").files[0],
reader = new FileReader();
var entityBytes = reader.readAsArrayBuffer(file);
reader.onloadend = function () {
alert(reader.result);
}
var xhr = new XMLHttpRequest();
var url = "/api/upload/e2j";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/octet-stream");
xhr.responseType = "json";
xhr.onload = function (e) {
var response = xhr.response;
alert(response);
}
xhr.send(reader.result);
}
Jersey:
#Path("/upload")
public class ParserHandler {
#POST
#Path("/e2j")
#Consumes(MediaType.APPLICATION_OCTET_STREAM)
#Produces(MediaType.APPLICATION_JSON)
public String entityToJsonTwoElectricBoogaloo(byte[] entityPayload) {
System.out.println(entityPayload.length);
}
Whenever I print length to the console, the length is always 0, when it should be 439. What am I doing wrong?
there is no need to use the filereader, you can just send the blob with xhr
function sendFile() {
var file = document.getElementById("entityFileField").files[0];
var xhr = new XMLHttpRequest();
var url = "/api/upload/e2j";
xhr.open("POST", url);
xhr.setRequestHeader("Content-type", "application/octet-stream");
xhr.responseType = "json";
xhr.onload = function (e) {
var response = xhr.response;
alert(response);
}
xhr.send(file);
}
Found the solution! Just moved everything but send and initialisations of file and FileReader into the xhr.onload function!
EDIT: Forgot to post my solution.
function postEntity() {
var output = document.getElementById("response");
var file = document.getElementById("entityFileField").files[0];
var jsonResponse;
var r = new FileReader();
r.onloadend = function(e) {
var data = r.result;
var xhr = new XMLHttpRequest();
var url = "/api/upload/entitytojson";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/octet-stream");
xhr.responseType = "json";
xhr.onload = function (e) {
if (xhr.response != null) {
jsonResponse = JSON.stringify(xhr.response);
output.innerHTML = jsonResponse;
}
else {
alert("Invalid Entity File");
}
}
xhr.send(data);
}
r.readAsBinaryString(file);
}

msgpack - unpack data from php service using js

Hi have created a XMLHttpRequest and get the resp by using the following code.
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.responseType = "text";
xhr.onload = function ()
{
debugger;
var resp = xhr.response;
var result = msgpack.unpack(resp);
};
but the response in undefined. I have checked the service from iOS and it is working fine.
Fixed by the following code. Set response type = arraybuffer.
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.responseType = "arraybuffer";
xhr.onload = function ()
{
var resp = xhr.response;
var uintDataArray = new Uint8Array(resp);
var strBytes = "";
for (var i = 0; i < uintDataArray.length; i++)
{
strBytes += String.fromCharCode(uintDataArray[i]);
}
var result = msgpack.unpack(strBytes);
};

Download Binary Files with Javascript

I want to download binary files using Javascript.
I have a REST service that returns the binary data and i want to know if its possible to show the binary file, whichever the file extension.
This is my current code:
var xhr = new XMLHttpRequest;
xhr.open("GET", requestUrl);
xhr.addEventListener("load", function () {
var ret = [];
var len = this.responseText.length;
var byte;
for (var i = 0; i < len; i++) {
byte = (this.responseText.charCodeAt(i) & 0xFF) >>> 0;
ret.push(String.fromCharCode(byte));
}
var data = ret.join('');
data = "data:application/pdf;base64," + btoa(data);
window.open(data, '_blank', 'resizable, width=1020,height=600');
}, false);
xhr.setRequestHeader("Authorization", "Bearer " + client.accessToken);
xhr.overrideMimeType("octet-stream; charset=x-user-defined;");
xhr.send(null);
Thanks!
Have a look at the MDN article on XMLHttpRequest.
If you set the response of the XMLHttpRequest to ArrayBuffer you could do the following:
var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "arraybuffer";
xhr.onload = function () {
if (this.status === 200) {
var blob = new Blob([xhr.response], {type: "application/pdf"});
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
};
xhr.send();
Option 2:
You could use Blob as the response of the XMLHttpRequest. And then maybe save it in the FileSystem (FileSystem API)
It may look like:
var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "blob";
xhr.onload = function () {
onDownloaded(this);
};
xhr.send();
Option 3:
If you only want to download and "show" images you can easily do this like so:
var img = new Image();
// add the onload event before setting the src
img.onload = function() {
onImageDownloaded(img);
}
// start the download by setting the src property
img.src = requestUrl

Categories

Resources