I am receiving an XmlHttpRequest's response in my code, which is a binary stream of a file. The response has the correct size and mimetype. I would like to download this file to disk, by issuing the typical browser prompt for saving files. I have the following script in place which works perfectly fine in Chrome. It fails for IE though.
var url = /my_rest_url/;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function (e) {
if (xhr.readyState == xhr.DONE) {
var blob = xhr.response;
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
}
xhr.send();
The failure happens on the window.open() call, where IE fails with an exception that says "access is denied". I have researched for hours on end without finding a solution which works for me. I have seen some recommendations to use a 'hidden iframe' to start the download, but it hasn't worked out for me. Has anyone ever made something like this work in IE? Would be glad to get some ideas.
ps/ I know blob and createObjectURL are relatively new. And even though they are supported by IE10 and above, I would really feel better to get rid of these and achieve this an 'old-school' way, if there is any.
Related
I'm surprised to see that this is hard to do, but i haven't found a single way to do that.
Basically i have a directory that contains:
--index.html
--script.js
--file.xml
And i want to read the content of the file.xml to a JS string for parsing.
The only method i found of doing so was by using a synchronous xmlhttp object which is disabled by default in my browser.
Is there another (preferably easy) way of reading a file to a string in js?
So, I might be a little late to the party, but this is to help anybody else who's been ripping his/her hair out looking for a solution to this.
First of all, CORS needs to be allowed in the browser if you're not running your HTML file off a server. Second, I found that the code snippets most people refer to in these kind of threads don't work for loading local XML-files. Try this (example taken from the official docs):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', true);
xhr.timeout = 2000; // time in milliseconds
xhr.onload = function () {
// Request finished. Do processing here.
var xmlDoc = this.responseXML; // <- Here's your XML file
};
xhr.ontimeout = function (e) {
// XMLHttpRequest timed out. Do something here.
};
xhr.send(null);
The method (1st arg) is ignored in xhr.open if you're referring to a local file, and async (3rd arg) is true by default, so you really just need to point to your file and then parse the result! =)
Good luck!
I am trying to download and show the contents of a remote file inside an iFrame , and succeeded in all browsers except for IE(i am trying with IE 10).
I have used XMLHttpRequest,Blob,CreateOBjectUrl APIs to complete the process.
In IE i am not able to view the file content inside the iFrame and also no particular error messages appeared on console as well.
I had pasted my code at the bottom of this thread , and a step by step explanation as below
Getting the download document url & corresponding mime
type(Perfectly fine in all broswers).
Invoking XMLHttp Request , a
Http GET Async call ,as response type as 'arraybuffer' (Perfectly
fine in all browsers) Upon completing the XMLHttpGet below 3 steps are
executing.
Creating a blob using the proper mimetype ;(Perfectly fine in all other browsers, specially verified the blob by downloading it in IE using MSSaveOrOpenBlob method).
4.InOrder to bind the blob contents to the iFrame , create the blob url using "createObjectURL" (Perfectly fine in all browsers , but in IE we are not getting a perfect URL).
Finally binding the URL with the iFrame for display.
Code snippet below.
// Getting the document url and mime type ( Which is perfectly fine )
var downloadUrl=finalServerURL + "DocumentService.svc/GetItemBinary?id=" + itemId + "&version=" + version;
var mimeTypeForDownload = responseStore.mimeTypes[currentlySelectedObject.fileExtension];
window.URL = window.URL || window.webkitURL;
//Defining the XML Http Process
var xhr = new XMLHttpRequest();
xhr.open('GET', downloadUrl, true);
xhr.responseType = 'arraybuffer'; //Reading as array buffer .
xhr.onload = function (e) {
var mimeType = mimeTypeForDownload;
var blob = new Blob([xhr.response], { type: mimeType });
// Perfect blob, we are able to download it in both IE and non-IE browsers
//This below url from createObjectURL,
//Working perfectly fine in all non-IE browsers, but nothing happening in IE
var url = window.URL.createObjectURL(blob);
document.getElementById(documentContentiFrameId).setAttribute("src", url);
};
xhr.send;
Please let me if you get any information on this , would be really helpful.
I came to know that its not possible in IE to get a proper URL for your blob entries , none of my attempts are get succeeded.
My alternative solutions,
1)go for pdf.js , an open source javascript library , which allows to render pdf binaries and equivalent pdf blobs.
2)Write your own viewers by utilizing the open PDF libraries , which will be time consuming , and more learning efforts involved.
Thanks,
Vishnu
I have a webworker that is producing a CSV for downloading, and to conserve memory I only have it return the URL it produces from teh blob..
My worker code looks something like::
var blob = new Blob([ResultOfSomeWork()],{type:'text/csv'});
URL.createObjectURL(blob);
self.postMessage({url:blob.url});
My goal is to just be able to download it in firefox and chrome this is very easy as I can just set up an invisible <a> and have it be clicked to download it.
For IE10 I want to use msSaveBlob but I need a blob which I don't want to transfer.
How can I download a object dataurl in IE10?
So I found a solution that works. Apparently, I can XHR and read the content back in my main thread.
worker.onmessage = function(event){
var url = event.data.url;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType='blob';
xhr.onload = function(){
msSaveBlob(xhr.response, fileName +'.csv');
};
xhr.send();
}
While this feels extremely complicated it works well in practice and is really fast.
I'm trying to upload a blob URL generated by getUserMedia to the server.
Someone else wanted to do the same thing, and that question has been answered.
I am using the same code for the XHR request as the person who answered that question, but I'm getting a 404. I made a fiddle, and the same thing happens when you look at the console. I have a live example on my site as well, and the same thing happens.
Here is the piece of code that needs some TLC:
function XHR(){
var xhr = new XMLHttpRequest();
xhr.open('GET',record.src); //404 ???
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200){
//do some stuff
result.innerText = this.response;
}
};
xhr.send();
}
Everybody else seems to be able to do this, because this has been discussed before.
Exhibit A
Exhibit B
I'm using ChromeOS, 41.0.2252.2 dev. What exactly is going on, and why can't I get the blob?
I'm almost certain the media in a MediaStream isn't saved anywhere, just thrown away after use.
There is a API in the works to record streams, MediaRecorder .
Only Firefox has the most basic implementation of this so it isn't usable as yet.
If you're implementing this on a mobile device you can use a file input with the capture attribute.
<input type="file" accept="video/*" capture>
function XHR(){
var xhr = new XMLHttpRequest();
xhr.open("GET","record.src",true); // adding true will make it work asynchronously
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200){
//do some stuff
result.innerText = this.response;
}
};
xhr.send();
}
Try now! it should work.
look at this post:
Html5 video recording and upload?
What you are missing is the declaration of what "blob" is. First thing this person does inside the .onload function() is
var blob = new Blob([this.response], {type: 'video/webm'});
I would like to make a google chrome extension, however I have been rubbing my head on a problem all night. I have the following code giving me a problem:
var xhr = new XMLHttpRequest();
var resp;
xhr.open("GET", "http://www.roblox.com/catalog/json?Subcategory=16&SortType=3&ResultsPerPage=10", true);
xhr.onload = function () {
resp = JSON.parse(xhr.responseText);
}
xhr.send();
I'm attempting to obtain some JSON data. If I replace this section of code with var resp = //(The actual JSON data itself), then the extension works just fine.
How can I fetch this JSON data correctly, and still have it compactable with anyone who downloads my extension?
Sorry if there's an obvious answer, I'm still new to Javascript.
Thanks!
Try setting the content type. Not all browsers use the same default.
xhr.setRequestHeader("Content-Type", "*/*");