My requirement is to import a html table to a CSV file. The code below gets called when the Download to CSV button is clicked in my web page. This works fine in chrome however in firefox it does nothing.
input.addEventListener('click', function (e) {
var fileName = cntrySel.value + '-Data.csv';
var a = document.createElement('a');
var data=$('#output').table2CSV({delivery:'value'});
blob = new Blob([data], { type: 'text/csv' }); //new way
var csvUrl = URL.createObjectURL(blob);
a.download = fileName;
a.href = csvUrl;
a.click();
a.setAttribute('onClick','');
e.preventDefault();
});
In firefox debugger, I can see the above function is getting triggered upon click but a.click() does nothing in FF whereas it downloads the csv file in chrome.
Any help is appreciated.
Soon after I posted this question, I came across this link Dynamically created ahref click event not working in firefox or safari? which has the answer.
Related
I am using a recent version of ANGULAR and all I want to achieve is to close the window when the download is finished.
It is supposed to work like this: when the user clicks on a link it opens this window that makes the download start and then it closes when download is finished, so that the close of the window doesn't stop the download.
I got this all sorted out for the main browsers except IE11, but I really need this to work on IE11.
This is what I have:
startDownload(filename: string, filecontent: string) {
let blob = DownloadUtils.b64toBlob(filecontent, "application/pdf");
let blobUrl = window.URL.createObjectURL(blob);
var downloadID = (new Date()).getTime();
var a = document.createElement('a');
a.setAttribute('href', blobUrl + "#downloadID=" + downloadID);
a.setAttribute('download', filename);
this.cookiePattern = new RegExp(("downloadID=" + downloadID), "i");
this.checkCookies();
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(blobUrl);
}
checkCookies() {
if (document.cookie.search(this.cookiePattern) >= 0) {
open('', '_self').close(); // download complete -> close window
return;
}
setTimeout(this.checkCookies, 500);
}
I was inspired by: https://laracasts.com/discuss/channels/javascript/using-javascript-to-check-if-a-file-has-been-downloaded
The problem with IE11 is that it doesn´t allow the download of blob URLs, I guess.
IE11 forces the use of:
window.navigator.msSaveBlob(blob, filename);
But with this I cant use the queryString "downloadID" to detect the end of download.
I also tried FileSaver.js but didn´t work.
I also tried to set:
a.setAttribute('href', 'data:application/pdf;base64,' + filecontent + "#downloadID=" + downloadID);
Which works, except on IE11 again. I get this error:
"The data area passed to a system call is too small."
NOTE: The problem isn't closing the page, but knowing when to close.
I could use a timeout for IE11, but I rather not.
Can you please help?
I generated an XML String in JavaScript and I need to download it as a file. I tried both answers provided in here.
Answer 1
Answer 2
Both answers work perfectly fine on MacOS Safari, iOS Safari and Raspbian Chromium, but when I try to download within the PWA on the iPad iOS 12.1.4, it does simply nothing. No Errors in console either.
If I try downloading in a new tab, it just shows a white screen and nothing happens.
EDIT:
I've done some testing involving iOS 13.
It appears to be working on iOS 13, yet even the html5 attribute 'download' to specify the file name works.
I ran into a possible bug though;
Using href for download pops up the iOS sharing menu but it does not let you close it. In order to use the app again, it needs to be closed.
Using window.open() it will let you close the sharing menu but the file name is not supported. Also a possible bug?
Anyway when I add target='_blank' to the href, it still does not let you give the option to close the sharing menu.
EDIT 2
I came to a workaround for iOS 13 standalone PWA in case the bugs mentioned in the EDIT above will not be fixed:
function download(content)
{
var file = new Blob([content],
{
type: 'text/xml;charset=UTF-8'
});
var reader = new FileReader();
reader.onload = function()
{
var popup = window.open();
var link = document.createElement('a');
link.setAttribute('href', reader.result);
link.setAttribute('download', 'filename.xml');
popup.document.body.appendChild(link);
link.click();
}
reader.readAsDataURL(file);
}
I came to a workaround for iOS 13 standalone PWA in case the bugs mentioned in the EDIT above will not be fixed:
function download(content)
{
var file = new Blob([content],
{
type: 'text/xml;charset=UTF-8'
});
var reader = new FileReader();
reader.onload = function()
{
var popup = window.open();
var link = document.createElement('a');
link.setAttribute('href', reader.result);
link.setAttribute('download', 'filename.xml');
popup.document.body.appendChild(link);
link.click();
}
reader.readAsDataURL(file);
}
I need to download pdf's from one of our online resources.There is no built in function to batch download.The only way to do it is to navigate to each pdf file, click to open, then click download.
There are several thousand files and this would take a very long time to do.
I got around this in the past using javascript. I gathered all the links to the pdfs, put them in a csv, and had the code loop through each link, download, and move onto the next link.
Unfortunately, I have lost that code and my efforts to recreate it have been unsuccessful.
I have tried everything in this article: How to download PDF automatically using js?
I have tried the code from this article (which I'm pretty sure is what I did before): https://www.convertplug.com/plus/docs/download-pdf-file-forcefully-instead-opening-browser-using-js/
This is what I think should work...per the second article I referenced above
function download_file(fileURL, fileName) {
var link = document.createElement('a');
link.href = fileURL;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
}
var fileURL = "link/to/pdf";
var fileName = "test.pdf";
download(fileURL,fileName);
The code above is just to test download one file from a hardcoded URL. If it worked as intended, when the page is loaded, it should download the pdf from the provided url. Instead, it doesn't do anything on load or refresh.
Any suggestions?
Please check
https://stackoverflow.com/a/18983688/6923146
click me
Another one
https://stackoverflow.com/a/45905238/6923146
function download(url, filename) {
fetch(url).then(function(t) {
return t.blob().then((b)=>{
var a = document.createElement("a");
a.href = URL.createObjectURL(b);
a.setAttribute("download", filename);
a.click();
}
);
});
}
download("https://get.geojs.io/v1/ip/geo.json","geoip.json")
download("data:text/html,Hello Developer!", "HelloDeveloper.txt");
I hope it helpfull
https://www.convertplug.com/plus/docs/download-pdf-file-forcefully-instead-opening-browser-using-js/
You must add link element to DOM
function download_file(fileURL, fileName) {
var link = document.createElement('a');
link.href = fileURL;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
var fileURL = "https://cdn.sstatic.net/clc/img/jobs/bg-remote-header-sm.png";
var fileName = "test.pdf";
download_file(fileURL, fileName); // fix function name
Link must be in same origin
The download attribute on anchor was ignored because its href URL has a different security origin.
I need help. I have an angular app and by using DocRaptor want to generate PDF and save it as file. But I cant trigger the dialog to save file in Safari with any method what I have found on Stack Overflow. Those methods open file in current browser tab and replace site html or open file in new tab. No one cant shows the dialog. Here the examples what I have already tried to use. Environment MacOS - EL Capitan. Safari 9.0.3
Solution #1
var content = 'file content for example';
var blob = new Blob([ content ], { type : 'text/plain' });
$scope.url = (window.URL || window.webkitURL).createObjectURL( blob );
Example jsfiddle. Shows file in current tab. Replaces site. But works in Chrome.
Solution #2
<a target="_self" href="mysite.com/uploads/ahlem.pdf" download="foo.pdf">
Example jsfiddle. Doesnt work at all in Safari. Works in Chrome.
Solution #3
<a class="btn" ng-click="saveJSON()" ng-href="{{ url }}">Export to JSON</a>
and
$scope.saveJSON = function () {
$scope.toJSON = '';
$scope.toJSON = angular.toJson($scope.data);
var blob = new Blob([$scope.toJSON], { type:"application/json;charset=utf-8;" });
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href',window.URL.createObjectURL(blob));
downloadLink.attr('download', 'fileName.json');
downloadLink[0].click();
};
Example Code Snippet. Shows the file content instead of document's html.
Solution #4
function download(text, name, type) {
var a = document.getElementById("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
}
Example Code Snippet. Replace document with file content in Safari. Works in Chrome.
And similar Solution #5
function download(text, name, type) {
var a = document.createElement("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
a.click();
}
Example jsfiddle. Doesnt work at all in Safari. Works in Chrome.
Also I have tried to use libraries like:
FileSaver - It opens file in Safari instead of document. So you should click Cmd+S. Example.
If we use type 'pplication/octet-stream' the name of file will be unknown or there was be an error 'Failed to load resource: Frame load interrupted'. Issue.
Second library Downloadify - doesnt work in Safari at all. Issue.
Angular library nw-fileDialog - instead of save as it shows choose file. Issue.
DocRaptor has own example with jQuery.
Example with angular in jsfiddle. It works in Chrome but in Safari example doesnt work be cause of error with SAMEORIGIN
Refused to display 'https://docraptor.com/docs' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
But if we reproduce it on server and change url on 'https://docraptor.com/docs.pdf' it works and open file in new tab and automatically download the file so you cant choose a folder and after download user see white empty screen tab in browser. If we specify form target="_self" it will work perfect, but console will have an error 'Failed to load resource:'.
I will appreciate any help with this problem.
Thanks.
Regards.
Try using Blob file for this:
// Buffer can be response from XMLHttpRequest/Ajax or your custom Int32 data
function download(buffer, filename) {
var file = new Blob([buffer], {
type: 'application/octet-stream' // Replace your mimeType if known
});
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var converted = e.target.result;
converted.name = filename;
converted.webkitRelativePath = filename;
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = converted;
};
fileReader.onerror = function(e) {
throw new Error('Something is wrong with buffer data');
};
fileReader.file = file;
fileReader.readAsDataURL(file);
}
It basically uses filebuffer and download that as an iframe content. Make sure to hook correct mime type so that safari security system will recieved analyse filetype.
Ideally, Solution #2 would be the answer, but the download attribute does not yet have cross-browser support.
So you have to use a <form> to create the download. As you noted, DocRaptor's jQuery example uses this technique.
The SAMEORIGIN error is actually because JSFiddle is running the code in an iFrame with their origin settings. If you run this straight from your Angular application, you shouldn't have any problems.
Anchor tag not downloading file in IE, instead it gives the option to search for app in app store to open file. For chrome and FF this code is working fine. I don't know this is happening in windows 7 or not as I am using windows 8.1 and windows 7 don't have option for apps.
var a = document.createElement("a");
a.href = filepath;
a.download = filename;
a.click();
Any help will be highly appreciated.
Thanks.
Directly quoting from SOpost
Internet Explorer does not presently support the Download attribute on A tags.
See http://caniuse.com/download and http://status.modern.ie/adownloadattribute; the latter indicates that the feature is "Under consideration" for IE12.
this might help:
var blob = new Blob([response.responseText], { type: headers['content-type'] });
if (navigator.msSaveOrOpenBlob) {
//Launches the associated application for a File or Blob saving for non webkit based browser such as safari or IE
navigator.msSaveOrOpenBlob(blob, "cvSummary.xml");
}
else {
//code for webkit based browser
var link = document.createElement('a');
document.body.appendChild(link);
link.style = "display: none";
var url = window.URL.createObjectURL(blob);
link.href = window.URL.createObjectURL(blob);
link.download = "cvSummary.xml";
link.dataset.downloadurl = ["text/xml", link.download, link.href].join(':');
link.click();
window.URL.revokeObjectURL(url);
}