Not able to Download ICS file in safari browser - javascript

I am trying to download ICS file in all the browsers.
I am able to download ICS file in chrome but not in safari. Here is the javascript code that i used.
if(isChrome)
{
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=fileName+".ics";
link.click()
}
if(!isChrome)
{
` alert("not chrome");
var downloadLink = document.createElement('a');
downloadLink.setAttribute('href', 'data:application/octet;charset=utf-8,' + escape(data));
var fileName = fileName+'.ics';
downloadLink.setAttribute('download', fileName);
var clk = document.createEvent("MouseEvent");
clk.initEvent("click", true, true);
downloadLink.dispatchEvent(clk);
document.body.appendChild(downloadLink);
downloadLink.dispatchEvent(clk);
//download(data, fileName+".ics", "text/calendar");
}
In Safari browser the generated file is getting downloaded but that file name is not getting appended. The filename i am getting is "Unknown" but the size of the file is 3KB and the content is there only the filename and extension is not getting added to the file.
Please let me know how i can solve this issue.
Thanks in advance

You should specify blob type. { type: 'text/calendar' }
const blob = new Blob([data], { type: 'text/calendar' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename + ".ics" ;
link.click();
Use this to download the file successfully, but you have to manually add it to the calendar. Safari does not include ics in a list of safe files and it will not be opened automatically.

If the problem is that you're using safari 10.1 or below the problem might be that it doesn't like the download attr.
http://caniuse.com/#feat=download

Related

Converting arraybuffer to blob for downloading as excel file in Chrome

I am trying to create an excel file that is downloadable from both Firefox and Chrome from an Angular 2+ environment. I have it working perfectly in firefox, but everything i try just doesn't work in Chrome - it downloads the file but when you open it throws an error - "Excel cannot open this file because the file format or file extension is not valid..".
I've tried to set my post responseType as 'arrayBuffer' and then creating a blob then downloading that, with no success. I've tried responseType as:
1)'blob'
2)'blob' as 'json'
3)'blob' as 'blob'
and passing it through to my component that way. Nothing seems to work on Chrome, everything works on Firefox though.
Here are some of my functions i have used to try get Chrome to open this excel.
downloadBlob(data: Blob, fileName: string) {
//output file name
//detect whether the browser is IE/Edge or another browser
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
//To IE or Edge browser, using msSaveorOpenBlob method to download file.
window.navigator.msSaveOrOpenBlob(data, fileName);
} else {
//To another browser, create a tag to downlad file.
const url = window.URL.createObjectURL(data);
const a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
}
blobToFile(data: Blob, fileName: string) {
const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';
const url = window.URL.createObjectURL(data);
a.href = url; a.download = fileName; a.click();
window.URL.revokeObjectURL(url);
}
downloadArray(data, fileName: string) {
var blob = new window.Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
window.URL = window.URL || window.webkitURL;
var url = window.URL.createObjectURL(blob);
window.location.href = url;
}
I've even tried to use the FileSaver.js plugin to save my blob with the oneliner
saveAs('blob', 'filename');
but everything wont read when opening from chrome. Any suggestions would be much appreciated.
Consider removing revokeObjectURL(). This test works and downloads in Chrome: https://batman.dev/static/70844902/
function downloadBuffer(arrayBuffer, fileName) {
const a = document.createElement('a')
a.href = URL.createObjectURL(new Blob(
[ arrayBuffer ],
{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }
))
a.download = fileName
a.click()
}

Angular Javascript export CSV. Is there a way specify the file extension consistently in Mac and Windows

I have the following line of code:
window.location.href = "data:text/csv;base64," + csvdata
that set to export csv data. it works on Mac with the extension "csv", but on windows it doesn't recognize as csv file. is there a way to specify the file extension?
Use navigator.msSaveBlob in IE, and .download for others.
var blob = new Blob([csvdata], {
type: "text/csv;charset=utf-8;"
});
var fileName = 'data.csv';
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName);
} else {
var downloadLink = document.createElement("a");
downloadLink.href = window.URL.createObjectURL(blob);
downloadLink.download = fileName;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}

blob not downloading in safari

i'm trying to download a csv file, however it seem to work in all browsers except safari? how come is that. in safari it is just showing it in the browser?
Here is my code:
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var blob = new Blob([data], {type: "text/csv;charset=utf-8"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
setTimeout(function(){
window.URL.revokeObjectURL(url);
}, 100);
};
}());
Your using the HTML 5 download attribute on the anchor tag which Safari doesn't support.
http://caniuse.com/#feat=download
It's probably best to link to the file and set headers like so to tell the agent to download rather than display.
Content-Type: text/csv
Content-Disposition: attachment; filename="whatever.csv"

exporting to csv file is not working in ie 11

var link = document.createElement("a");
link.id="lnkDwnldLnk";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
var csv = CSV;
blob = new Blob([csv], { type: 'text/csv' });
var csvUrl = window.webkitURL.createObjectURL(blob);
var filename = "CCUDetail_";
$("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
$('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
Here it is showing script error that blob is undefined in ie 11.
Use this for IE,
var IEwindow = window.open();
IEwindow.document.write('sep=,\r\n' + CSV);
IEwindow.document.close();
IEwindow.document.execCommand('SaveAs', true, fileName + ".csv");
IEwindow.close();
For more information i have written tutorial on that,
see - Download JSON data in CSV format Cross Browser Support
Hope this will be helpful for you.

How to download a base64-encoded image?

I have a base64-encoded image from the server for which I want to force the download through JavaScript. Is is possible?
If you want to download it using JavaScript (without any back-end) use:
window.location.href = 'data:application/octet-stream;base64,' + img;
where img is your base64 encoded image.
If you want to allow the user to specify a file name, use the download attribute of the a tag:
<a download="FILENAME.EXT" href="data:image/png;base64,asdasd...">Download</a>
Notice: The download attribute is not supported by very old browsers
Simple way to do this with Javascript...
var a = document.createElement("a"); //Create <a>
a.href = "data:image/png;base64," + ImageBase64; //Image Base64 Goes here
a.download = "Image.png"; //File name Here
a.click(); //Downloaded file
It is so simple just use function below:
// Parameters:
// contentType: The content type of your file.
// its like application/pdf or application/msword or image/jpeg or
// image/png and so on
// base64Data: Its your actual base64 data
// fileName: Its the file name of the file which will be downloaded.
function downloadBase64File(contentType, base64Data, fileName) {
const linkSource = `data:${contentType};base64,${base64Data}`;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
I found this solution from the sourcecode of how Chrome takes full-page screenshots.
const base64string = "";
const pageImage = new Image();
pageImage.src = 'data:image/png;base64,' + base64string;
pageImage.onload = function() {
const canvas = document.createElement('canvas');
canvas.width = pageImage.naturalWidth;
canvas.height= pageImage.naturalHeight;
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.drawImage(pageImage, 0, 0);
console.log(canvas, pageImage)
saveScreenshot(canvas);
}
function saveScreenshot(canvas) {
let fileName = "image"
const link = document.createElement('a');
link.download = fileName + '.png';
console.log(canvas)
canvas.toBlob(function(blob) {
console.log(blob)
link.href = URL.createObjectURL(blob);
link.click();
});
};
I don't know whether am late to answer this, but I think the better solution could be this.
Create a file from the base64string
const convertBase64ToFile = (base64String, fileName) => {
let arr = base64String.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let uint8Array = new Uint8Array(n);
while (n--) {
uint8Array[n] = bstr.charCodeAt(n);
}
let file = new File([uint8Array], fileName, { type: mime });
return file;
}
Install File Saver from npm with
npm install file-saver
Import File Saver
const { saveAs } = require('file-saver');
/// OR
import { saveAs } from 'file-saver';
Using File Saver download the file
const downloadBase64Data = (base64String, fileName) => {
let file = convertBase64ToFile(base64String, fileName);
saveAs(file, fileName);
}
If this Answer has worked for you please upvote it and mark it as correct to help others easily find it
You can try this :
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Download Text File DataURL Demo</title>
<style>
body{ font: menu; }
</style>
<script src='//js.zapjs.com/js/download.js'></script>
</head>
<body>
<h1>Download Text File DataURL Demo</h1>
<main></main>
<script>
download("data:application/octet-stream;base64,YOUR BASE64URL", "dlDataUrlText.jpeg", "application/octet-stream;base64");
</script>
</body>
</html>
download tag downloads the image using the script included.
For reference you can try this URL : http://danml.com/download.html
In my Angular App, I am getting the base 64 files from server.
In Html:-
<button type="button" (click)="downloadFile(fileName,base64data,fileType)"></button>
In Ts:-
downloadFile(fileName:string,data: any,fileFormat:string): void {
const linkSource = 'data:'+fileFormat+';base64'+data;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
If you already have it in base64, add the image tag in front of the base64. attach it to the element
png64 = "data:image/" + png64;
$('#downloadPNG').attr('href', png64);
Add the file name that you want when downloading to the download tag.
<a download="chart.png" id="downloadPNG">Export img</a>
In my React App, I was getting the base 64 images from an API, I stored it in a global prop and downloaded it with the help of <a> tag.
<a href={`data:application/octet-stream;base64,${this.props.base64image}`} download={"imageName"}>Click to Download the image</a>
At first: This question is extremly browser dependent! I tried many, so I came up to answer this question that way:
You should put the base64-Data inside the src-Tag of an IMG-Element:
How to display Base64 images in HTML?
Then you can right click the Image and click "Save Image..." (or similar) in these browsers:
Chrome 79
Edge 44
Firefox 71
IE 11
Safari 13
Also on Android with Chrome and Firefox.
Biggest file working was 23 MB PNG-File in IE 11 and Safari 13. But Firefox and Chrome did also work for 86 MB JPEG.

Categories