Javascript readAsArrayBuffer from url - javascript

Is it possible to read binary file from url?
var url = 'http://example.com/image/abc.jpg';
var reader= new FileReader();
reader.addEventListener('load', function () {
// whatever
});
reader.readAsArrayBuffer(url);
Above example is not working (url is not a object).
var file = new File([""], "url");
is empty

You have to use HTTP GET to get the file. Maybe this is what you need?
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.response);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
httpGetAsync("http://cdn.androidbeat.com/wp-content/uploads/2015/12/google-logo.jpg", res => console.log(res))

URL in your case is a string object. You need to use HTTP get in this case. HTTP GET request in JavaScript? and read the response.

Related

XMLHttpRequest return from a function before response is back

I have a function as the code below, I am trying to send a file through XMLHttpRequest to the server and then store it in DB and retrieve the id of the file in DB and make an object of ids.
The problem is that the function exits a lot before I got the response back from the server to store it in the object therefore the object doesn't store those values.
I know that I need make the XHR asynchronous but it doesn't change the result, I have also tried timeout or using a different platform like Ajax but still, it didn't work.
async function getFileObj() {
var FileObject = {}
for (let key1 in PObj) {
FileObject[key1] = {}
for (let key2 in PObj[key1]) {
FileObject[key1][key2] = {}
for (let key3 in PObj[key1][key2]) {
const formData = new FormData();
formData.append('myFile.png', filesObjDB[key1][key2][key3]);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'url', true);
xhr.onreadystatechange = async function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200)
var id = await xhr.response.text();
FileObject[key1][key2][key3] = parseInt(id)
}
xhr.responseType = 'blob';
xhr.send(formData);
}
}
}
return FileObject;
}
Help would be very appreciated!
You are not awaiting the request. To make the existing code wait for the result, you'd need to wrap the outdated callback-based code in a promise and await that (and also I don't think getting the response text of an XHR works as you showed, I changed it now):
// This is just to demonstrate what was immediately wrong
// with the existing code - it's not the best solution! See below.
FileObject[key1][key2][key3] = await new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
var id = xhr.responseText;
resolve(parseInt(id));
}
};
xhr.send(formData);
});
Note there is no error handling yet, if the request fails everything will just hang.
But at that point, it doesn't actually make sense to use XHR in the first place! It's a lot more straightforward to use fetch, which has a promise API out of the box:
const response = await fetch(url, { method: 'POST', body: formData })
FileObject[key1][key2][key3] = parseInt(await response.text())

How to get a certain line from xml from other webpage (url) in js?

const xhrRequest = new XMLHttpRequest();
xhrRequest.onload = function()
{
dump(xhrRequest.responseXML.documentElement.nodeName);
console.log(xhrRequest.responseXML.documentElement.nodeName);
}
xhrRequest.open("GET", "/website_url.xml")
xhrRequest.responseType = "document";
xhrRequest.send();
I'm trying to request a xml page from a page, but i'm unable to get certain line from xml in javascript. Thank you!
You can easily send requests to other pages with an AJAX http request found here: https://www.w3schools.com/js/js_ajax_intro.asp
Here is an example function:
function SendRequest(){
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
// Success
}
};
xmlhttp.open("GET", "example.com", true);
xmlhttp.send();
}
Now, about getting a value from the xml document, you can use .getElementsByTagName(). Notice that this is an array of elements so you have to append an index such as [0]
This would go inside the onreadystatechange of the http request
if(this.readyState == 4 && this.status == 200){
let xmlDocument = this.responseXML;
console.log(xmlDocument.getElementsByTagName("TestTag")[0].childNodes[0].nodeValue);
}
So if the xml document had an element like:
<TestTag>Hello</TestTag>
the function would print Hello

Doing multiple XMLHttpRequest from different url

I'm trying to use XMLHttpRequest to get data from two different localhost ports. It will run the request as soon as the page loaded. And I will run a function as soon as it finish getting the data from the 2 ports. But so far, only can get the data from local port 1000. I have check the ports already but no problem. The problem must have been the javascript.
js:
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:1000/data1";
var info1;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
info1 = jQuery.parseJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
var xmlhttp1 = new XMLHttpRequest();
var url1 = "http://localhost:2000/data2";
var info2;
xmlhttp1.onreadystatechange = function () {
if (xmlhttp1.readyState == 4 && xmlhttp1.status == 200) {
info2 = jQuery.parseJSON(xmlhttp1.responseText);
reload(info1, info2);
}
}
xmlhttp1.open("GET", url1, true);
xmlhttp1.send();
function reload(info1, info2) {
alert("success");
// processing the data
}
Is it that something wrong with the javascript?

download multiple images from the server with XMLHttpRequest using javascript

I am using the XMLHttpRequest method to get the url of a single image from the server to download, save and then retrieve it from android local storage, and I have succeeded to get it working for a single image url; NOW I AM STUCK on figuring a way to download multiple images from the server using the same method. Can anyone show spare me a way or two ?
Thanks in advance!!!
here the code which I am using to download a single image
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
console.log(xhr);
xhr.onload = function (e) {
console.log(e);
if (xhr.readyState == 4) {
console.log(xhr.response);
// if (success) success(xhr.response);
saveFile(xhr.response, 'images');
}
};
xhr.send();
Assuming you have list of urls from which images can be downloaded, you can use a simple for loop and store XMLHttpRequest variable in an array.
var xhrList = [];
var urlList = ['example.com/image1',
'example.com/image2',
'example.com/image2'];
for (var i=0; i< urlList.length; i++){
xhrList[i] = new XMLHttpRequest();
xhrList[i].open('GET', urlList[i], true);
xhrList[i].responseType = "blob";
console.log(xhrList[i]);
xhrList[i].onload = function (e) {
console.log(e);
if (this.readyState == 4) {
console.log(this.response);
// if (success) success(this.response);
saveFile(this.response, 'images');
}
};
xhrList[i].send();
}

Ionic controller XMLHttpRequest function doesn't work

does somebody know why this doesn't work? I get a error message at 'request.status' in Ionic
.factory('Nieuws', function() {
var url = "http://echo.jsontest.com/ID/2/bericht/test";
var request = new XMLHttpRequest();
request.open("GET", url);
var nieuws;
request.onload = function () {
if (request.status = 200) {
nieuws = JSON.parse(request.responseText);
//console.log(nieuws);
}
};
You're trying to assign a value to a read only property when you need to be making a comparison.
Replace = with ==.

Categories