javascript download csv data in Safari - javascript

Is there anyway to download a csv string that I have created in my javascript in Safari?
EDIT: I do not want to (cannot) create a file on the server.
I have the following code, it will work fine on other browsers, but not on safari. The best that I can seem to make it do is open the data in a new window, but that is an awful UI experience for the user.
$("#csv").click(function(event) {
event.preventDefault();
navigator.sayswho = (function() {
var ua = navigator.userAgent, tem,
M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
return M[1];
})();
var download = function (content, fileName, mimeType) {
var a = document.createElement('a');
mimeType = mimeType || 'application/octet-stream';
mimeType = 'application/octet-stream';
if (navigator.msSaveBlob) { // IE10
return navigator.msSaveBlob(new Blob([content], {
type: mimeType
}), fileName);
} else if ('download' in a) { //html5 A[download]
a.href = 'data:' + mimeType + ',' + encodeURIComponent(content);
a.setAttribute('download', fileName);
document.body.appendChild(a);
setTimeout(function () {
a.click();
document.body.removeChild(a);
}, 66);
return true;
} else { //do iframe dataURL download (old ch+FF):
if (navigator.sayswho == 'Safari') {
var uri = 'data:text/csv;charset=utf-8,' + escape(content);
var link = document.createElement("a");
link.href = uri;
link.target = "_blank";
link.style = "visibility: hidden";
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
else
{
var f = document.createElement('iframe');
document.body.appendChild(f);
f.src = 'data:' + mimeType + ',' + encodeURIComponent(content);
setTimeout(function () {
document.body.removeChild(f);
}, 33333);
return true;
}
}
}
//csv_content is my string that has the csv data in it.
download(csv_content, moment().format("YYYY_MM_DD_HH_mm") + '.csv', 'text/csv');
});
In Chrome and in FireFox, it works as expected. I saw some answers using FileSaver.js (https://stackoverflow.com/a/14858315/1758023), but the comments say this is not working (and I couln't make it work either).

Try using the following js function.
function download()
{
window.location = '<<your file name with full path>>';
//for ex. function download()
//window.location = 'mobilepayreport.xls';
}

I also had the issue in safari.You can create and download the csv file in safari.But until your file is not physically stored on any location it does not show the file name and type in download popup(it always shows unknown).So I suggest pass the data as html in server side code using ajax and create a file and and with response of that call create the link of file which you stored from server side code.download the file and then you can delete this file.

Related

doesn't able to download image in react using blob

I have a QR code that is coming from the database in the base64 format. I have to download this image on a button click. I use this function to download the image on button click. the function runs successfully and I able to download the image, but when I try to open the image, an error message comes in 'Photos', 'Paint' type application says the file is not supported. I use same code for download an CSV data and it is working perfectly fine.
What is the error in this code?
export const downloadCSV=(data, filename,image)=>
{
var downloadLink;
if(image !== null && image === true)
{
var dataType = 'image/png';
}
else{
var dataType = 'application/vnd.ms-excel';
}
var filename = filename;
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', data], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
downloadLink.href = 'data:' + dataType + ', ' + data;
downloadLink.download = filename;
downloadLink.click();
}
}

Downloading Json FIle using javascript

This is my json data that I currently get when i convert a xml file:
{"mxGraphModel":{"root":{"mxCell":[{"_id":"0"},{"_id":"1","_parent":"0"},{"mxGeometry":{"_x":"200","_y":"100","_width":"100","_height":"100","_as":"geometry"},"_id":"2","_style":"shape=ellipse","_vertex":"1","_parent":"1"},{"mxGeometry":{"_x":"520","_y":"250","_width":"100","_height":"100","_as":"geometry"},"_id":"3","_style":"shape=triangle","_vertex":"1","_parent":"1"},{"mxGeometry":{"_x":"900","_y":"460","_width":"100","_height":"100","_as":"geometry"},"_id":"4","_style":"shape=cylinder","_vertex":"1","_parent":"1"},{"mxGeometry":{"_x":"310","_y":"450","_width":"100","_height":"100","_as":"geometry"},"_id":"5","_style":"shape=actor","_vertex":"1","_parent":"1"},{"mxGeometry":{"_relative":"1","_as":"geometry"},"_id":"6","_edge":"1","_parent":"1","_source":"2","_target":"3"},{"mxGeometry":{"_relative":"1","_as":"geometry"},"_id":"7","_edge":"1","_parent":"1","_source":"5","_target":"3"},{"mxGeometry":{"_relative":"1","_as":"geometry"},"_id":"8","_edge":"1","_parent":"1","_source":"3","_target":"4"}]}}}
But when I download the same data as .json, I get this:
"{\"mxGraphModel\":{\"root\":{\"mxCell\":[{\"_id\":\"0\"},{\"_id\":\"1\",\"_parent\":\"0\"},{\"mxGeometry\":{\"_x\":\"200\",\"_y\":\"100\",\"_width\":\"100\",\"_height\":\"100\",\"_as\":\"geometry\"},\"_id\":\"2\",\"_style\":\"shape=ellipse\",\"_vertex\":\"1\",\"_parent\":\"1\"},{\"mxGeometry\":{\"_x\":\"520\",\"_y\":\"250\",\"_width\":\"100\",\"_height\":\"100\",\"_as\":\"geometry\"},\"_id\":\"3\",\"_style\":\"shape=triangle\",\"_vertex\":\"1\",\"_parent\":\"1\"},{\"mxGeometry\":{\"_x\":\"900\",\"_y\":\"460\",\"_width\":\"100\",\"_height\":\"100\",\"_as\":\"geometry\"},\"_id\":\"4\",\"_style\":\"shape=cylinder\",\"_vertex\":\"1\",\"_parent\":\"1\"},{\"mxGeometry\":{\"_x\":\"310\",\"_y\":\"450\",\"_width\":\"100\",\"_height\":\"100\",\"_as\":\"geometry\"},\"_id\":\"5\",\"_style\":\"shape=actor\",\"_vertex\":\"1\",\"_parent\":\"1\"},{\"mxGeometry\":{\"_relative\":\"1\",\"_as\":\"geometry\"},\"_id\":\"6\",\"_edge\":\"1\",\"_parent\":\"1\",\"_source\":\"2\",\"_target\":\"3\"},{\"mxGeometry\":{\"_relative\":\"1\",\"_as\":\"geometry\"},\"_id\":\"7\",\"_edge\":\"1\",\"_parent\":\"1\",\"_source\":\"5\",\"_target\":\"3\"},{\"mxGeometry\":{\"_relative\":\"1\",\"_as\":\"geometry\"},\"_id\":\"8\",\"_edge\":\"1\",\"_parent\":\"1\",\"_source\":\"3\",\"_target\":\"4\"}]}}}"
I find that there are unwanted "\" characters in the downloaded version. The code i use to download the data is:
function download(jFile) {
var text = jFile;
var result = "data:application/json," + encodeURI(text);
var a = document.createElement("a");
a.style = "display: none";
a.href = result;
a.download = "flowChartJson.json";
if (window.navigator.msSaveBlob !== undefined) {
window.navigator.msSaveBlob(blob, a.download);
window.URL.revokeObjectURL(result);
return;
}
document.body.appendChild(a);
requestAnimationFrame(function() {
a.click();
window.URL.revokeObjectURL(result);
document.body.removeChild(a);
});
}
Where am I going wrong?
Thanks in advance for your help.

Angular save file as csv result in Failed- network error Only on Chrome

I'm using the following code to save file as csv.
$scope.saveCSVFile = function (result)
{
var a = document.createElement('a');
a.href = 'data:application/csv;charset=utf-8,' + encodeURIComponent(result.data);
a.target = '_blank';
a.download = $scope.getFileNameFromHttpResponse(result);
document.body.appendChild(a);
a.click();
$scope.isReportInProgress = false;
};
The file is working on most of the cases but for some reason when the file is larger than 10MB i get "Failed - Network Error".
It happens only on chrome.
I tried to search the web for this issue and couldn't find anything relevant.
Can you think of an idea why does it happens? or maybe use a different save file method that will work on chrome/firefox/IE instead of my function?
I was finally used this one, hope it can help the next one encounter this issue:
var blob = new Blob([result.data], {type: 'text/csv'});
var filename = $scope.getFileNameFromHttpResponse(result);
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);
}
I had a similar problem, but had to serve a zip file, sent from the server in base64 format. What did the trick for me:
function downloadBlob(data, filename) {
const blob = new Blob([new Buffer(data, 'base64')], {type: 'application/octet-stream'});
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
} else {
const elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
window.URL.revokeObjectURL(elem.href);
document.body.removeChild(elem);
}
}
return (
{/* ... */}
<a href="#" onClick={() => {downloadBlob(report.zip, `${report.filename}.zip`)}}>
Download <b>{report.filename}.zip</b>
</a>
{/* ... */}
);
I left the function because like the fact that it revokes the URL after serving the file.

Getting corrupted word document when using FileSaver and Blob in angularjs

I am using angular-file saver service https://github.com/alferov/angular-file-saver for downloading files. Download is good but when try to open word document I am getting file is corrupted and word cannot open it and if put my api directly in browser file is good when I open it so I suppose blob is doing something for this issue... For .txt files I am not getting corrupted it is good only for .docx and for .jpeg or .png. Below is my short code for downloading files.
function downloadDocument(fileId, fileName, documentExt) {
var deferred = $q.defer();
var id = encodeURIComponent(fileId);
Restangular.one('download?fileId=' + id).get().then(function(data) {
var file = new Blob([data]);
if (documentExt && documentExt !== 'undefined') {
FileSaver.saveAs(file, fileName + '.' + documentExt);
}
else {
FileSaver.saveAs(file, fileName);
}
});
return deferred.promise;
}
you can use give below code to save your file--
function downloadDocument(fileId, fileName, documentExt) {
var deferred = $q.defer();
var id = encodeURIComponent(fileId);
Restangular.one('download?fileId=' + id).get().then(function(data) {
// try to use data.data or data in blob object
var file = new Blob([data.data], {
type: 'application/octet-binary'
});
var fileUrl = URL.createObjectURL(file);
// for IE 10+
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, fileName+'.'+documentExt);
} else {
var element = document.createElement('a');
element.href = fileUrl;
element.setAttribute('download', fileName+'.'+documentExt);
element.setAttribute('target', '_blank');
document.body.appendChild(element);
element.click();
}
});
return deferred.promise;
}

Can we save file from html page in android device using javaScript

I am prompting window on desktop to save file on local device by using following code
if (finalResult == '') {
alert("Invalid data");
return;
}
var result2 = nameObject.personalInfo[0].Name;
var result3 = nameObject.personalInfo[0].Number;
var fileName = result2 + result3;
var uri = 'data:text/csv;charset=utf-8,' + escape(finalResult);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
location.reload();
By this user can get CSV into excel. Will same code work for android devices?
If not then please suggest me alternatives.
Thank you

Categories

Resources