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();
}
Related
Hi, I am trying to extract something from an API, which should return me a string with the recent prices for Ethereum.
After that I would like to parse the string and drop all data, so that only the latest price is returned.
This is the code I have so far, however it does not return anything and I am stuck on this and how to parse the code.
Any help is greatly appreciated! Thanks.
{
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.kraken.com/0/public/Ticker?pair=ETHEUR', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}
}
};
You're not sending the request. You need to add xhr.send(); to send the request. Here is the sample request.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.kraken.com/0/public/Ticker?pair=ETHEUR', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log(this.responseText);
}
};
xhr.send();
After creating your xhr and adding the proper callbacks to it, make sure to invoke xhr.send(). The response from that endpoint seems to be a JSON object, so you can invoke JSON.parse() on the response to turn it into a javascript object that you can work with.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.kraken.com/0/public/Ticker?pair=ETHEUR', true);
xhr.onreadystatechange = function() {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// Parse JSON response
var data = JSON.parse(xhr.responseText);
// Use the object however you wish
console.log(data);
}
}
xhr.send();
You must call the xhr.send(); function to actually send the request. Otherwise you have just initialized the request and also set up the callback function to handle the response but no request to the API is sent.
I have an array of file to save by using a loop and i generate the name of each file. I want to save file directly (in non interactive way) without asking me to confirm. How can i do ?
Here is my code for saving file
var url = img.src.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; //Set the response type to blob so xhr.response returns a blob
xhr.open('GET', url , true);
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
var filesaver = require('file-saver');
filesaver.saveAs(xhr.response, nameFile); // nameFile the name of file to be saved
}
};
xhr.send(); //Request is sent
Finally, i find a solution, instead of saving file, i write it by creating a new one.
for (var i = 0; i < tabForm.length; i++) {
var imgData = $('#affichageqr')[0].childNodes[1].childNodes[0].src;
var data = imgData.replace(/^data:image\/\w+;base64,/, '');
fs.writeFile(qrcode.getNomQRCode()+'.jpeg', data, {encoding: 'base64'}, function(err){
if (err) {
console.log('err', err);
}
console.log('success');
});
}
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.
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
While I was trying to create a workaround for Chrome unsupporting blobs in IndexedDB I discovered that I could read an image through AJAX as an arraybuffer, store it in IndexedDB, extract it, convert it to a blob and then show it in an element using the following code:
var xhr = new XMLHttpRequest(),newphoto;
xhr.open("GET", "photo1.jpg", true);
xhr.responseType = "arraybuffer";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
newphoto = xhr.response;
/* store "newphoto" in IndexedDB */
...
}
}
document.getElementById("show_image").onclick=function() {
var store = db.transaction("files", "readonly").objectStore("files").get("image1");
store.onsuccess = function() {
var URL = window.URL || window.webkitURL;
var oMyBlob = new Blob([store.result.image], { "type" : "image\/jpg" });
var docURL = URL.createObjectURL(oMyBlob);
var elImage = document.getElementById("photo");
elImage.setAttribute("src", docURL);
URL.revokeObjectURL(docURL);
}
}
This code works fine. But if I try the same process, but this time loading a video (.mp4) I can't show it:
...
var oMyBlob = new Blob([store.result.image], { "type" : "video\/mp4" });
var docURL = URL.createObjectURL(oMyBlob);
var elVideo = document.getElementById("showvideo");
elVideo.setAttribute("src", docURL);
...
<video id="showvideo" controls ></video>
...
Even if I use xhr.responseType = "blob" and not storing the blob in IndexedDB but trying to show it immediately after loading it, it still does not works!
xhr.responseType = "blob";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
newvideo = xhr.response;
var docURL = URL.createObjectURL(newvideo);
var elVideo = document.getElementById("showvideo");
elVideo.setAttribute("src", docURL);
URL.revokeObjectURL(docURL);
}
}
The next step was trying to do the same thing for PDF files, but I'm stuck with video files!
This is a filler answer (resolved via the OP found in his comments) to prevent the question from continuing to show up under "unanswered" questions.
From the author:
OK, I solved the problem adding an event that waits for the
video/image to load before executing the revokeObjectURL method:
var elImage = document.getElementById("photo");
elImage.addEventListener("load", function (evt) { URL.revokeObjectURL(docURL); }
elImage.setAttribute("src", docURL);
I suppose the revokeObjectURL method was executing before the video
was totally loaded.