AJAX download not working - javascript

I have a valid url which I am trying to download using ajax.
What's wrong with the following code?
url = "https://firebasestorage.googleapis.com/v0/b/analyst-3206a.appspot.com/o/research_reports%2FNt7cXdWHFlQuwRcy8wo4B49VNeD3%2Fa?alt=media&token=5521f889-2737-4433-a279-f04999cdff22"
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();

you have to put createObjectURL
url = "https://firebasestorage.googleapis.com/v0/b/analyst-3206a.appspot.com/o/research_reports%2FNt7cXdWHFlQuwRcy8wo4B49VNeD3%2Fa?alt=media&token=5521f889-2737-4433-a279-f04999cdff22"
var a = document.getElementById("a");
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function (event) {
var blob = xhr.response;
var a = document.createElement("a"),
url = window.URL.createObjectURL(blob);
document.body.appendChild(a);
a.href = url;
a.download = "fileName." + blob.type;
a.click();
window.URL.revokeObjectURL(url);
};
xhr.open('GET', url);
xhr.send();

Related

How show file download progress using javascript?

I am using below code to download the file to browser.
function UserAction() {
var Url = " ";
var postData = new FormData();
var xhr = new XMLHttpRequest();
xhr.open('GET', Url, true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
var blob = xhr.response;
this.saveOrOpenBlob(blob,blobName);
}.bind(this)
xhr.send(postData);
}
function saveOrOpenBlob(blob,blobName) {
//var assetRecord = this.getAssetRecord();
var fileName = blobName;
var tempEl = document.createElement("a");
document.body.appendChild(tempEl);
tempEl.style = "display: none";
url = window.URL.createObjectURL(blob);
tempEl.href = url;
tempEl.download = fileName;
tempEl.click();
window.URL.revokeObjectURL(url);
}
I want to display the download progress, I am not using any html code. My application has standard button which accept javascript action. I dont have any custom ui.
With current condition user will not know whether the file is downloading or not if it is a large file.
How can I achieve this?
Use this:
function saveOrOpenBlob(url, blobName) {
var blob;
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET', url, true);
xmlHTTP.responseType = 'arraybuffer';
xmlHTTP.onload = function(e) {
blob = new Blob([this.response]);
};
xmlHTTP.onprogress = function(pr) {
//pr.loaded - current state
//pr.total - max
};
xmlHTTP.onloadend = function(e){
var fileName = blobName;
var tempEl = document.createElement("a");
document.body.appendChild(tempEl);
tempEl.style = "display: none";
url = window.URL.createObjectURL(blob);
tempEl.href = url;
tempEl.download = fileName;
tempEl.click();
window.URL.revokeObjectURL(url);
}
xmlHTTP.send();
}

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);
}
});
}

FileReader::readAsArrayBuffer, how to get length?

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?
}

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);
}

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