How to download a file programmatically using JS (Internet Explorer) - javascript

I have a web page where there is a button that when clicked, generates a (by doing a conversion from json) csv file that is downloaded by the browser. It essentially uses the logic from this jsfiddle. This all works in chrome, but in IE, nothing happens.
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
The issue seems to be that the download attribute of an anchor tag doesn't exist in Internet Explorer. I've been looking at numerous articles and SO posts, but I haven't found a coherent solution that I can use in the page.
How can the code from the jsfiddle be implemented in IE?

This is what I have used in the past. This handles IE and non-IE.
var filename = "file.txt";
var data = "some data";
var blob = new Blob([data], { type: 'text/csv' });
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else {
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}

Related

Download PDF From Rest API

I have the following text that i get from java with a get request.
GET: http://localhost:8101/raportet/Cinema.jasper
%PDF-1.4
%âãÏÓ
3 0 obj
<</Filter/FlateDecode/Length 1644>>stream
xœ½œ]SÛF†ïý+ö2½ˆ²_úêUÝ`Rh;étz¡`aDü‘H†ß•Ç
8ïJø5ã³ ôé<^Yþ<ø}20‘ˆÃHL¦ƒÑdð×#‹ãê·JH÷¨¾Ç©“ÅàÕ¡JŠÉåàÅ
..............
I want to download this file in frontend using js.
I tried a lot of methods but i cannot download it. Is there any method i can do it.
I've almost the same problem as this: Opening PDF String in new window with javascript
you can use this method if you want to show and download PDF in ReactJs
axios.get(exportUrl, {responseType:'blob'})
.then(response => {
// Create blob link to download
var blob = new Blob([response.data], { type: 'application/pdf' });
var URL = window.URL || window.webkitURL;
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.target = '_blank';
link.href = url;
link.setAttribute( //if you just want to preview pdf and dont want download delete this three lines
'download',
`Factor.pdf`,
);
// Append to html link element page
document.body.appendChild(link);
// Start download
link.click();
// Clean up and remove the link
link.parentNode.removeChild(link);
URL.revokeObjectURL(url);
})
}

How to show download as prompt on new window from bootstrap model?

For a normal HTML page I tried the below code which starts download in a separate window. When I use the same code for bootstrap modal form then it's not working. What else I need to do for implement same functionality in bootstrap modal ?
var newwin=window.open("",'newwindow','width=700,height=700, left=100,top=100,resizable=yes','_blank').document;
var link =newwin.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
you have used blob in window.URL.createObjectURL, which is undefined.
you can use this solution.
use code like this :
var newwin=window.open("",'newwindow','width=700,height=700, left=100,top=100,resizable=yes','_blank').document;
var link =newwin.createElement('a');
var blob = new Blob([json], {type: "octet/stream"});
link.href = window.URL.createObjectURL(blob);
link.download = fileName
window.location.assign(url);

Excel export not working on Firefox but working fine in google crome

The below given event is called to export the data in the table into an EXCEL , The code works like a charm in Chrome . In IE and Firefox i am not getting anything(File, error etc).
Kindly assist me to go forward and export the file in all the browsers
$("[id$=myButtonControlID]").click(function(e) {
var result = 'data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$=printHead]').html());
var link = document.createElement("a");
link.download = "Reports";
link.href = result;
link.click();
});
With Firefox you have to explicitly add the link element to the DOM before you can execute .click():
$("[id$=myButtonControlID]").click(function(e) {
var result = 'data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$=printHead]').html());
var link = document.createElement("a");
document.body.appendChild(link); // You need to add this line
link.download = "Reports";
link.href = result;
link.click();
});
The data: URI is supported from IE8. But it "cannot be used for navigation [...]" so I assume it will not work in an <a href="...">. See this link.

Angularjs/Restangular, how to name file blob for download?

For some reason this seems easier in IE than Chrome/FF:
$scope.download = function() {
Restangular.one(myAPI)
.withHttpConfig({responseType: 'blob'}).customGET().then(function(response) {
//IE10 opens save/open dialog with filename.zip
window.navigator.msSaveOrOpenBlob(response, 'filename.zip');
//Chrome/FF downloads a file with random name
var url = (window.URL || window.webkitURL).createObjectURL(response);
window.location.href = url;
});
};
Is there a way to do something similar to how IE10+ works? That is, I can specify a file name/type (will only be zip)?
As soon as you have your object url you can create an anchor and set the download attribute to the filename you want, set the href to the object url, and then just call click
var myBlob = new Blob(["example"],{type:'text/html'})
var blobURL = (window.URL || window.webkitURL).createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.download = "myfile.txt";
anchor.href = blobURL;
anchor.click();
Download attribute compatibility
Just use https://www.npmjs.com/package/angular-file-saver
Browser Support table can be seen here: https://github.com/eligrey/FileSaver.js/

Table to CSV without using download attribute as it is not supported on Safari browser

I am trying to export HTML table to CSV using JQuery.
I am able to export the data to CSV with below code,Succeeded in all browsers but not able to export in Safari(5.1.2) browser.
I tried with download attribute, but came to know Safari browser doesn't support download attribute.
Please let me know if there is work around?
var usersCSVData = [];
usersCSVData.push('LastName ','FirstName ', 'Login ','City ','State','Location ');
var fileName = "UserCSVdata.csv";
var buffer = usersCSVData.join("\n");
var blob = new Blob([buffer], {
"type": "text/csv;charset=utf8;"
});
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, fileName);
}
else {
var link = document.createElement("a");
if (link.download !== undefined) {
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style = "visibility:hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
I think this JavaScript library may be the solution you need:
https://github.com/eligrey/FileSaver.js
You will also need the blob.js dependency for Safari < 6.1

Categories

Resources