Downloading Json FIle using javascript - 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.

Related

Javascript: How to download csv file from a url

I have a url which has csv file. i want to download that file by JavaScript. during download i will provide file name and by that name file will be download in client pc. i tried below code which is not working. where i made the mistake. please give me hint.
function downloadFile(fileName, urlData) {
var aLink = document.createElement('a');
var evt = document.createEvent("HTMLEvents");
evt.initEvent("click");
aLink.download = fileName;
aLink.href = urlData;
aLink.dispatchEvent(evt);
}
downloadFile('Test.csv', 'https://testsite.com/targeting/Export/aa.csv');
Use
aLink.click();
instead of the Dispatch-event
I found code which worked. here is the code which i am following now.
var url = 'https://testsite.com/targeting/Export/aa.csv';
var a = document.createElement("a");
a.href = url;
fileName = url.split("/").pop();
alert(fileName);
a.download = fileName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
a.remove();

JAVASCRIPT: EDGE change extension of file download

I have a problems with Microsoft Edge: when I do the download edge changes the extension of the file that I just have downloaded. With Chrome and Firefox I don't have this problems... I attach the code that I use:
a = document.createElement('a');
a.href = "name.xxx";
a.target = '_blank';
a.download = "name.xxx";
a.type = ".icd";
document.body.appendChild(a);
a.click();
a.remove();
The structure of the file is an XML file, but it has his extension.
Can you help me??
I don't know if I'm late, but this is a solution that works, I had the same error and I was able to solve it.
var blob = new window.Blob([data], { type: 'application/pdf' });
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
var filename = url.substring(url.lastIndexOf('/') + 1);
a.href = url;
a.download = filename + '.pdf' || 'download';
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);

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.

how to generate html and css file dynamically using javascript for download by the user from string?

I have a css code and html code in a string and want to create a .html and .css file for download. Is it actually possible?
I've used this example but it prints all code exactly as string and not as real css/html code
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
http://jsfiddle.net/koldev/cW7W5/
Wow ok, I found the solution. Just remove first and last quotations. tada...
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var parsed = data.replace(/^['"].*['"]+/g, ''),
blob = new Blob([parsed], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
http://jsfiddle.net/cW7W5/1356/

javascript download csv data in Safari

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.

Categories

Resources