Safari 9 XMLHttpRequest Blob file download - javascript

Hello JavaScript gurus,
I need a file download functionality using XMLHttpRequest (with responseType="blob") that works in Safari 9+.
At the moment I'm using FileSaver.js like this:
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// using FileSaver.js to save blob
saveAs(xhr.response, filename);
// notify download finished, resolve promise
defer.resolve(true);
}
};
xhr.send();
which works fine in all main browsers but not in current version (9.x) of Safari.
I'll get a "Failed to load resource: Frame load interrupted". Usually a download is a zip file but I also tried to set "application/octet-stream".
I have one requirement: I need to know when then download has finished on client-side so using an iframe is no option (I guess).
I'm thankful for any hint how to download a file in Safari using XHR (no Flash).
Thanks,
Chris

Simple answer:
There is no solution!
See also: https://forums.developer.apple.com/message/119222
Thanks Safari ... my new almost IE6

Related

Angular download PDF on IOS mostly opens in same tab

I'm using file-saver in my angular application to download a PDF generated in my backend. The library generally works fine on desktop and android. But I don't seem to be able to download a file on IOS. file-saver doesn't, as stated in on the GitHub page, open the blob in a new Page either. it jus opens on the same page (not wanted). Funnily enough it works fine in safari (it opens a dialog that asks me to download and then downloads it without opening it). In any other browser (opera, firefox and chrome) it doesn't seem to work.
I've tried file-saver, downloadJ, creating an anchor tag myself together with the download attribute, using the application/octet-stream mime-type and several other solutions posted on the internet. All of these methods in most browsers just doe nothing or open the PDF blob in the same page instead of downloading it or opening it in a new tab (as file-saver states it would do on IOS).
I'm generating the PDF in a Google Cloud Function. Is there maybe a way to skip the whole client side of things and make the browser download the file directly from there?
Does anyone have another idea on how to download PDF's on mobile IOS (e.g. with a service worker or something)?
Thanks in advance
Best solution as per new chrome specification https://developers.google.com/web/updates/2018/02/chrome-65-deprecations
Vanilla JavaScript
public static downloadFile(url: string): void {
const xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = () => {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
const blobUrl = window.URL.createObjectURL(xmlHttp.response);
const e = document.createElement('a');
e.href = blobUrl;
e.download = blobUrl.substr(blobUrl.lastIndexOf('/') + 1);
document.body.appendChild(e);
e.click();
document.body.removeChild(e);
}
};
xmlHttp.responseType = 'blob';
xmlHttp.open('GET', url, true);
xmlHttp.send(null);
}
If you're using angular try this.
async downloadBrochure(url: string) {
try {
const res = await this.httpClient.get(url, { responseType: 'blob' }).toPromise();
this.downloadFile(res);
} catch (e) {
console.log(e.body.message);
}
}
downloadFile(data) {
const url = window.URL.createObjectURL(data);
const e = document.createElement('a');
e.href = url;
e.download = url.substr(url.lastIndexOf('/') + 1);
document.body.appendChild(e);
e.click();
document.body.removeChild(e);
}

Get URL from Blob in Internet Explorer using JavaScript

I need to print a PDF file which I obtain through a GET request in JavaScript. In order to do the actual printing I use PrintJS, which can be used to print from a specific PDF URL.
My code looks something like this:
printChart() {
var req = new XMLHttpRequest();
req.open('GET', 'http://localhost:8080/test.pdf', true);
req.responseType = 'blob';
req.onload = function (event) {
var blob = req.response;
var blobURL = window.URL.createObjectURL(blob);
printJS(blobURL);
};
req.send();
}
This works fine in Chrome, but the problem is it does not print anything in Internet Explorer (tested in IE 11). Apparently, window.URL.createObjectURL does not work properly in IE.
Although there is a msSaveOrOpenBlob method in IE but this doesn't help me very much, since I need to print the PDF, not to save it.

Upload an image to server using chrome extensions

I am doing a chrome extension capable of getting from a webpage an image, and after I got it, I'm trying to upload it to an intranet server automatically without user iteration.
I am doing this right now.
This is on Content_script.js
...
x = $(frame1).contents().find("#image");
chrome.extension.sendRequest(x[0].src);
...
This is on background.js
chrome.extension.onRequest.addListener(function(links) {
chrome.downloads.download( { url: links ,
conflictAction: "overwrite",
filename: "get_image.jpg" },
function(DescargaId) {
var formData = new FormData();
formData.append("doc", Blob, "~/Downloads/get_image.jpg");
var request = new XMLHttpRequest();
request.open("POST", "http://192.168.0.30/app_get_pictures/upload_img.php");
request.setRequestHeader("Content-Type", "multipart/form-data");
request.send(formData);
} );
This on upload_img.php
...
$uploaddir = $_SERVER['DOCUMENT_ROOT'].'/app_get_pictures/images/';
$uploadfile = $uploaddir . basename($_FILES['doc']['name']);
move_uploaded_file($_FILES['doc']['tmp_name'], $uploadfile);
...
With this, I already download the image successfully to the local machine, but can't upload the image to the server.
It is possible to do this, or even if I can upload the image to the server directly without download it first to the local machine.
Note: I don't have any tag form on a popup page in the extension solution, and I don't have a popup page neither, because as I already said, I don't need any iteration from the user.
Thanks for your help!
Thanks to https://stackoverflow.com/users/934239/xan I resolved this problem using his advise, here is the resulting working code.
...
// With this I can download or get content image into var blob
var xhr = new XMLHttpRequest();
var kima = $(frame1).contents().find("#image");
xhr.open('GET',kima[0].src,true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = new Blob([this.response], {type: 'image/png'});
send_image(blob);
}
};
xhr.send();
....
// After the image is loaded into var blob, it can be send
// to the server side
function send_image(x){
var formData = new FormData();
formData.append("doc", x);
var request = new XMLHttpRequest();
request.open("POST", "http://192.168.0.30/app_get_image/upload_img.php");
request.send(formData);
}
All this code into the content_script of the chrome extension. Also the code of the background using API download isn't needed anymore.
Hope this could works for anybody else.
Thanks again.
Besides the fact that the callback of downloads.download does NOT indicate that the file is already downloaded (only that the download is queued)..
formData.append("doc", Blob, "~/Downloads/get_image.jpg");
What do you think this code does? Documentation, for reference.
The second parameter is supposed to hold the data of the file; the third parameter is just the file name for the purposes of naming anonymous data (e.g. in a Blob)
Instead, you pass the Blob object itself; not an instance of Blob with the data.
In fact, with this architecture, you won't be able to upload the file, since at no point does chrome.downloads API give you access to the file's contents, and you can't just access a file on a disk by filename (which is what I think you thought this code would do).
To actually access the data, you need to request it yourself with XHR (or Fetch API if you want to be "modern"). Then, you get the response object which you can request to be a Blob. Then, you can both upload the blob and invoke chrome.downloads together with createObjectURL to "download" it from your extension's memory.

Fetching BLOB in Chrome Android

I'm struggling to fetch an HTML5 video using xhr2 and blob responseType with Chrome on Android 4.2. The code works perfectly on Chrome and Firefox desktop and on Firefox Android 4.2 (with FF desktop, I use a webm video instead of the mp4).
// Taking care of prefix
window.URL = window.URL || window.webkitURL;
// This function download the video
var loadVideo = function() {
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', addVideoFile, false);
xhr.open('GET', "videos/myvideo.mp4" , true);
xhr.responseType = 'blob';
xhr.send();
};
// this function sets the video source
var addVideoFile = function() {
if(4 == this.readyState && 200 == this.status) {
var video = document.getElementById('vid'),
blob = this.response;
video.src = window.URL.createObjectURL(blob);
console.log('video ready');
}
};
loadVideo();
Can anyone explain me why this does not work with Chrome on Android? If I plug my phone to use the remote debugging, the console will display 'video ready', suggesting that the video was downloaded but it's impossible to play it, video is just a black screen.
Also, this code works if I use it to fetch images instead of video. Is there a limitation I'm not aware of, preventing to download Blob above a certain size? (My video is 1.5 MB).
Thanks you very much for your help!
This is most certainly a bug. If you get something that works on Desktop Chrome but not Android then 99.5% of the time it is an issue we need to fix.
I have replicated your issue http://jsbin.com/uyehun/1 and I have filed the bug too https://code.google.com/p/chromium/issues/detail?id=253465
Per http://caniuse.com/bloburls, for Android 4.0-4.3 you need to use window.webkitURL.createObjectUrl() instead of window.URL.createObjectUrl().
This will let you generate a blob url, though I haven't actually been able to get a video element to play such an url.

XMLHttpRequest to read an external file

I want to retrieve the data contained in a text file (from a given URL) through JavaScript (running on the client's browser).
So far, I've tried the following approach:
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;
But it only works for Firefox. Does anyone have any suggestions to make this work in every browser?
Thanks
IT works using xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); in IE older versions. Chrome, Firefox and all sensible browsers use xhr
Frankly, if you want cross browser compatibility, use jquery
its pretty simple there:
var text="";
$.get(url, function(data){text=data;//Do something more with the data here. data variable contains the response})
var xhr = new XMLHttpRequest();
xhr.open('POST', '/uploadFile');
var form = new FormData();
form.append('file', fileInput.files[0]);
xhr.send(form);
It was previously impossible to upload binary data with XMLHttpRequest object, because it could not stand the use of FormData (which, anyway, did not exist at that time) object. However, since the arrival of the new object and the second version of XMLHttpRequest, this "feat" is now easily achievable
It's very simple, we just spent our File object to a FormData object and upload it

Categories

Resources