I have created below code which takes a JSON object and convert it to comma separated through the ConvertToCSV function. My question is then how i can take the variable csvData and download it as a csv file?
This code is already in a function which is being executed on button click
var jsonObject = JSON.stringify(data);
var toCSV = ConvertToCSV(jsonObject);
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(toCSV);
use blob to store it locally and then download it. e.g
http://jsfiddle.net/koldev/cw7w5/
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);
};
}());
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
saveData(data, fileName);
this http://jsfiddle.net/e5ggkkur/1/ will work in firefox
Related
I am working on displaying an image in blob
const file = new Blob([response.data], { type: 'image/png' });
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
console.log('fileURL', fileURL);
const image = document.createElement('img');
I am getting this response
PNG
IHDR2²OósRGB®ÎégAMA±üa pHYsÃÃÇo¨dã¼IDATx^ìý=ô<Ó¶Þ;Ðزg
cõ-EVÙÚÜòfã·#cV0¡\¡5È·Eüü$
]EGâ¹AD" èî÷½þûeü÷_ý×ð\¸³µ°ñ F\¸³µ°ñ F\¸³µ°ñ F\¸³µ°ñ FáË¥ßçòüù«&Þv~ÑTU?ÿ^Ý}öòóÜï×'sµùÔ¤|¼þåúE8ñp
ÎÛ3Î0
¹Þuv]áÌäZ×G#¬Ïv\f.ý{ý>ã¦ñï÷õÈõÁÛÅØã·n6«ÿÞpÙ.2ßƹod
ÕEk+bv|_Hß5yÏçnØ1C´ìOÑÞøVÛ|¯
¤=ûsÔ_}BKíWÊó÷¿ç¯×ò_Þòu¸ÈÜ\dF¾a
¯FXí¸.Í\"øãñXÈ|8°àmÇýØa)#
F;L æ Øñæá_ðɾ´o»ìÔq#ºMxVÍ_±S.|íËs¿4×â7÷="/2GýÝù¹uyZ{c6Â×·°ãÛÆyqÎ_\ÁFøÎ)¼>a}¶àº¸r)Ý
ÄÛ® ÖáÌÁÁ\à"ó'â7|ú®HNë'/Õû
D ¶³c.!lÿȶËhê¾ü"sÆß4ò#^¦¬XxcvÒ׷̽ÀEf$.í7a}¶àº4s)úáñtøÖEÛ´´ve¬í`Ê"UWäÃÛèÁ¿X}½2få¯âH²×n£Îy)U|Íg]O½{þ«}Ï®¹JÈ-ýðkÙʯóR¸/ZLBd[NN±¨ùÖÌ¥x}³è:#"9¯yoL÷ÿBÎj¸Õvöú_æ´v8çï.òú©Cµ-/óÊõÑ _{¹³æb[.êòRÙÖ£'lµo¦¬aò/ÌÕ1>ÿ¶ª<hPù½nüä7Ûzéú]Ïúgó=ó´ÞÛúºÓ¾KéåSÀÅ [¥8ìµÛ¸üí®õFxOáõÑë³×¥KËG1ýÿF&Êw\c´Û6¶Éðqò&¹mYÐÜ#ÝÄØtÓYÇÈ>Ó'´«6"áW±5k>\¥ñ[ëñîùkö[1X}Íãq{1K_1oÓç÷1ãÕ8t*Þå+V±]/G´v5ZI¨Úɹ¼Æ5
µç°½Ö¿cþîÄÊLò#¬1CƳ¾zrgô·mbÄjïøÛX9N½oû½â²ÖhÏZßlë]ßo=Ku³MâáôÙ;V¼W·õN}¹¾ýíÛH¨>4ðÆ`>çyÐ9x¾¿¢_;GC[
¯FXí¸.¾\J;Ýu¼í2ñÃccçp^iL|CJ~\vvobú<ª
Ê··á¾Þ9k¸ðÞùöwÆ ö£ôUcgû"þÏZ5Ú7xoìq*ò¡Zå#UÛySÞkc+{gsÛw¥Me;û²ÆS×_Ò&wzßwÉýçSoçÙÂ_#2Vïÿ¶3F¬FÏoýVì÷{¾YûÇï4WÍnÀ²]û·wãÖ;ÙëÅÂ>¯´g6®qÕüìåD·ñøëYë°®^°>Ûp]þ4´õáUíøH}{cø63}ccªXòâÙØ%yCZÛx6±óÉã/ýºkyïü
ûyncÖTYü¯b`Ì)|ÜrY÷9ÁÛªßA7úÖGSÿ]sßrSôÉöëÒË
¥Ms.Ù'ÕfÏ_ï¼
´<`Äï-¯+f#|ÈÜÑsqä·1bõÖñßddÐ7k¿óø½å¨Gíêùéy7·wܾ5¦k\#.¢ÂSx}4ÂúlÀuùÓ\ÒHãÀí\Yîæªí£§ÞÄV±AiÞóñHÜÏgyBØR:ñîù«ö¶¦r®úF޳ث¦®=+°\Ö}Î0_µ4y§o
ÝXi(ßv}ïGDrkåËË%_íò}æÿnÙ<ìoÖväÉ _ÿâÛV1â°g|1\Ìñ{ë³cmZ߬ùÎí·½ß[¶Óóìßéy_onÏe!å%ïçÏq׸Æ<´ý¾÷týu¯õFxNáõÑë³×åOsI; ["ÅhçÛÈä¸qDüL´¡o¸cçCIïÚ¶ß;Ã~sMùsßÅÿ*¿9½»#Ç;°voõâFãÛ®|<(ùÁî³ãð=Úa±mÎå'Ù¬:HùÛAËN«×C¾úrgì·ÝÀùñ;hùNi¼ßóÍÚïöûlm},ÛÕóÓóðÆ[>çö|öKnÒ²/¿]ãqù
ìPx}4ÂúlÀuùÓ\j~àv»6²î :Ã61µ
ÛÄbÞ&;v>5}ÛoxrfMc1cvµ9;õặbZÞ/ëú: ßìÛ7VªøUúÉyNtN;iîÖþbÌÍ°|ÿÿÕ
®õ·V¯G|uæÎÐo»Sãwáv8¶Ý=߬ýîßud¯}n³úwvÇ×ÛsÙ¹pîÛs«~,&ïÄ寽\ëñúhõÙëò§¹¤Æ#Ñ ßF¹7ź{h×ßàmb_IðÐ6ä+ï£æì±yPÞ=ï¦v$ÙðlóÃ7¦Ö. ÆX°q)Ù¾×ñóàöm/v+ñ=ó5çz[=;+ùÀg1Ù+6,Û$¿Ö
÷·6^ùêË=e_7ê·Ý¢õ=÷Ç/kXwíÚq~/8µ÷ö3ým½ëúÞÓo9ÇûW¿bóÜ<¯7·çµ¿æ"+Ô×®qY,qì5æ
ßȺ¸üÝ£¡-×G#¬Ïv\?Í¥øᱬuðròKþè½Yl©´¥Â¸Mlû°ø¨mtÜNSÝùlvøØ÷Îß°ãÂ×´ö=ôIµòÃ1fDɯ}³îsMséÏÓ²Kö_í7È·o¬8Ú·(öóÂß&õÖïV¬ñ,´q95l¯¾üþÖmJm-ZyPèæ#fG}uä'¾ítÙ=ãù8óMä·+â+íê~&Zï"¿¹4«mfC]÷Ãó8¾ÞÜÏ~ªó¼I}÷¬igÜ3>Ø?»ßÉwähxOáõÑë³×¹ôÙèóBÞ°Ô|é"£¬-|æùóÅ|Ûú.gk?aâ¹ôáärÕUù3àïÅø©/|W¼È|Ýú&gk?a}¶àº ¾ñ+û¥X¾$|ÆÁ%/2o;Sßào°AáõÑë³×¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¢K?Ïð/á_ÿff¬á=þÑ´4?Ïsÿøz}Ä2ßç?þU{ß7?¾!׿ÏÈð´´ß;Ög;®K+ :¾¯¿Èhÿ¢ñZÈ¿Û±)ßèût9ýÿXc\dt¼>bO
.2À.2`#^°>Ûp]¾*þ½~>!zAþzþÆøóÅÇ¿ß× bó"S?K¾:sg¬ÎýcâÛà|¼)Ny>xóããóè¯÷àSà"6fk?aý«Ä'øh¾*¾úÀ_ÏÿSDlþMKåó"³x.A×ò_
±:÷OooðñVà"3¿ÞOØýõ¯à£iå<TÒFÚÄÒÙÍcÿ(ë~j·|#¬¶Y»ô§¬tĨ5>ßÈ×vÄÊGî·NOÌ?À×p×ZãocXgÇjò¼û"Sæb%m®%gÔxr[æ8+¾G×?0ÂG¯º}oOYñδ+¦[ï"Ü6¿ÐµÁÉïµHÝ1#Û)~Br{,>imø÷×9Ã×qoÝbkWç*¾ÎqÏÚü×÷¹6ñ×wlîjxæîÍpKB^Px}4ÂúlÀuiåR}øäd]5lÞê&IýÃ&Ê4Mp²
V{7ïÖm|2bWósE´çÖÔK·¿>¾§ó$;ÆÒ0ÆwÛtÄ¢G¯Ñ¶6oÇÔ~Js®|Äÿ3s_·->¦g¥Möëí)ó,´ÞIÛʳ¦
When I reffer some stackoverflow answers I understood my response is wrong. my questions is how to get correct binary response ..
You can use XMLHttpRequest() or fetch() to get response as Blob
let url, w;
let request = fetch("/path/to/image");
request.then(function(response) {
return response.blob() // return `Promise` which resolves to `Blob` of response
})
.then(function(blob) {
url = URL.createObjectURL(blob);
w = window.open(url);
})
.catch(function(err) {
console.log(err)
});
let url, w;
let request = new XMLHttpRequest();
request.open("GET", "/path/to/image");
request.responseType = "blob"; // set `responseType` to `"blob"`
request.onload = function() {
url = URL.createObjectURL(blob);
w = window.open(url);
}
request.onerror = function(e) {
console.log(e);
}
request.send(null);
$http.get(ur1, {
responseType: 'blob'
}).then(function (res) {
this.download(res)
}, function (err) {
conseole.log(err)
})
}
};
this.download = function (data) {
var type = data.headers('Content-Type'),
content = data.data,
fileName = data.headers('x-ms-meta-originalname'),//Get the file name
blob = new Blob([content], {type: type}),
url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.target="_self";
a.download = fileName;
a.click();
a = undefined;
}
Additinal Details here: http://angularjstricks.blogspot.in/2017/03/download-file-from-server-with-http-in.html
I have a similar question to this question(Javascript: Exporting large text/csv file crashes Google Chrome):
I am trying to save the data created by excelbuilder.js's EB.createFile() function. If I put the file data as the href attribute value of a link, it works. However, when data is big, it crashes Chrome browser. Code are like this:
//generate a temp <a /> tag
var link = document.createElement("a");
link.href = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + encodeURIComponent(data);
link.style = "visibility:hidden";
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
My code to create the data using excelbuilder.js is like follows:
var artistWorkbook = EB.createWorkbook();
var albumList = artistWorkbook.createWorksheet({name: 'Album List'});
albumList.setData(originalData);
artistWorkbook.addWorksheet(albumList);
var data = EB.createFile(artistWorkbook);
As suggested by the answer of the similar question (Javascript: Exporting large text/csv file crashes Google Chrome), a blob needs to be created.
My problem is, what is saved in the file isn't a valid Excel file that can be opened by Excel. The code that I use to save the blob is like this:
var blob = new Blob(
[data],
{type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,"}
);
// Programatically create a link and click it:
var a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = fileName;
a.click();
If I replace the [data] in the above code with [Base64.decode(data)], the contents in the file saved looks more like the expected excel data, but still cannot be opened by Excel.
I had the same problem as you. It turns out you need to convert the Excel data file to an ArrayBuffer.
var blob = new Blob([s2ab(atob(data))], {
type: ''
});
href = URL.createObjectURL(blob);
The s2ab (string to array buffer) method (which I got from https://github.com/SheetJS/js-xlsx/blob/master/README.md) is:
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
The answer above is correct. Please be sure that you have a string data in base64 in the data variable without any prefix or stuff like that just raw data.
Here's what I did on the server side (asp.net mvc core):
string path = Path.Combine(folder, fileName);
Byte[] bytes = System.IO.File.ReadAllBytes(path);
string base64 = Convert.ToBase64String(bytes);
On the client side, I did the following code:
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.onload = () => {
var bin = atob(xhr.response);
var ab = s2ab(bin); // from example above
var blob = new Blob([ab], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'demo.xlsx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
xhr.send();
And it works perfectly for me.
I've found a solution worked for me:
const handleDownload = async () => {
const req = await axios({
method: "get",
url: `/companies/${company.id}/data`,
responseType: "blob",
});
var blob = new Blob([req.data], {
type: req.headers["content-type"],
});
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = `report_${new Date().getTime()}.xlsx`;
link.click();
};
I just point a responseType: "blob"
This works as of: v0.14.0 of https://github.com/SheetJS/js-xlsx
/* generate array buffer */
var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'});
/* create data URL */
var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'}));
/* trigger download with chrome API */
chrome.downloads.download({ url: url, filename: "testsheet.xlsx", saveAs: true });
Here's my implementation using the fetch api. The server endpoint sends a stream of bytes and the client receives a byte array and creates a blob out of it. A .xlsx file will then be generated.
return fetch(fullUrlEndpoint, options)
.then((res) => {
if (!res.ok) {
const responseStatusText = res.statusText
const errorMessage = `${responseStatusText}`
throw new Error(errorMessage);
}
return res.arrayBuffer();
})
.then((ab) => {
// BE endpoint sends a readable stream of bytes
const byteArray = new Uint8Array(ab);
const a = window.document.createElement('a');
a.href = window.URL.createObjectURL(
new Blob([byteArray], {
type:
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}),
);
a.download = `${fileName}.XLSX`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
})
.catch(error => {
throw new Error('Error occurred:' + error);
});
Solution for me.
Step: 1
<a onclick="exportAsExcel()">Export to excel</a>
Step: 2
I'm using file-saver lib.
Read more: https://www.npmjs.com/package/file-saver
npm i file-saver
Step: 3
let FileSaver = require('file-saver'); // path to file-saver
function exportAsExcel() {
let dataBlob = '...kAAAAFAAIcmtzaGVldHMvc2hlZXQxLnhtbFBLBQYAAAAACQAJAD8CAADdGAAAAAA='; // If have ; You should be split get blob data only
this.downloadFile(dataBlob);
}
function downloadFile(blobContent){
let blob = new Blob([base64toBlob(blobContent, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')], {});
FileSaver.saveAs(blob, 'report.xlsx');
}
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
let sliceSize = 1024;
let byteCharacters = atob(base64Data);
let bytesLength = byteCharacters.length;
let slicesCount = Math.ceil(bytesLength / sliceSize);
let byteArrays = new Array(slicesCount);
for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
let begin = sliceIndex * sliceSize;
let end = Math.min(begin + sliceSize, bytesLength);
let bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
Work for me. ^^
try FileSaver.js library. it might help.
https://github.com/eligrey/FileSaver.js/
This answer depends on both the frontend and backend having a compatible return object, so giving both frontend & backend logic. Make sure backend return data is base64 encoded for the following logic to work.
// Backend code written in nodejs to generate XLS from CSV
import * as XLSX from 'xlsx';
export const convertCsvToExcelBuffer = (csvString: string) => {
const arrayOfArrayCsv = csvString.split("\n").map((row: string) => {
return row.split(",")
});
const wb = XLSX.utils.book_new();
const newWs = XLSX.utils.aoa_to_sheet(arrayOfArrayCsv);
XLSX.utils.book_append_sheet(wb, newWs);
const rawExcel = XLSX.write(wb, { type: 'base64' })
// set res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
// to include content type information to frontend.
return rawExcel
}
//frontend logic to get the backend response and download file.
// function from Ron T's answer which gets a string from ArrayBuffer.
const s2ab = (s) => {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
};
const downloadExcelInBrowser = ()=>{
const excelFileData = await backendCall();
const decodedFileData = atob(excelFileData.data);
const arrayBufferContent = s2ab(decodedFileData); // from example above
const blob = new Blob([arrayBufferContent], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(fileBlob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement('a');
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location.href = downloadUrl;
} else {
a.href = downloadUrl;
a.download = 'test.xlsx';
document.body.appendChild(a);
a.click();
}
} else {
window.location.href = downloadUrl;
}
}
if you are using typescript then here is a working example of how to convert array to xlsx and download it.
const fileName = "CustomersTemplate";
const fileExtension = ".xlsx";
const fullFileName = fileName.concat(fileExtension);
const workBook : WorkBook = utils.book_new();
const content : WorkSheet = utils.json_to_sheet([{"column 1": "data", "column 2": "data"}]);
utils.book_append_sheet(workBook, content, fileName);
const buffer : any = writeFile(workBook, fullFileName);
const data : Blob = new Blob(buffer, { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;" });
const url = URL.createObjectURL(data); //some browser may use window.URL
const a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = fullFileName;
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 0);
I'm using angular 1.2.27, and I'm trying to download a file. It works perfect on chrome but on FF nothing happens, the request returns 200/ok and the success code runs, but that's it, no file is downloaded:
var fileLoaded = $q.defer();
$http.get(url, { responseType: 'arraybuffer' })
.success(function (data,status,hdr) {
var cd = hdr('Content-Disposition').split(';');
var fileName = '';
_.forEach(cd,function(d){
if(d.trim().indexOf('filename') >= 0){
fileName = d.split('=')[1].replace(/[\"]/g,'');
return false;
}
});
var file = new Blob([data]);
var wurl = $window.URL || $window.webkitURL;
var fileURL = wurl.createObjectURL(file);
console.log( 'fileURL:' , fileURL );
var a = document.createElement("a");
a.href = fileURL;
a.download = fileName;
a.target = "_self";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
wurl.revokeObjectURL(fileURL);
fileLoaded.resolve(true);
}).error(function (data) {
// console.error(data);
fileLoaded.reject(data);
});
return fileLoaded.promise;
}
The only difference i see is when i log the fileURL. on chrome it appears like this:
blob:http%3A//localhost%3A9000/e869aa88-8190-4d9d-a379-9ad977a09613
And on FF like this:
blob:http://localhost:9000/f36b7773-00bb-4ade-87be-8f197c41ccf8
But I assume this is just a console thing.
any idea what I'm doing wrong?
Putting an answer here for reference. Using FileSaver from #Satpal comment, i was able to solve it easily:
var fileLoaded = $q.defer();
$http.get(url, { responseType: 'arraybuffer' })
.success(function (data,status,hdr) {
var cd = hdr('Content-Disposition').split(';');
var fileName = '';
_.forEach(cd,function(d){
if(d.trim().indexOf('filename') >= 0){
fileName = d.split('=')[1].replace(/[\"]/g,'');
return false;
}
});
var file = new Blob([data]);
saveAs(file, fileName);
fileLoaded.resolve(true);
}).error(function (data) {
// console.error(data);
fileLoaded.reject(data);
});
return fileLoaded.promise;
}
It is not downloading csv file, it redirecting current page to another page (web page cann't be displayed)
This is code for downloading csv file
var fileName = "test";
var data = $(this).first(); //Only one table
var a = document.createElement('a');
a.href = 'data:' + mimeType + ';charset=utf-8,' + escape(data);
a.download = fileName;
a.style = 'display:none';
if (navigator.msSaveBlob) { // IE 10+
var blob = new Blob([data], {
"type": "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, fileName);
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
If I debug this code it ask for downloading a file after that go to the another page
You had special handling for IE browser.
But you need to put non-IE code in else block.
var fileName = "test";
var data = $(this).first(); //Only one table
var mimeType = 'text/csv';
var a = document.createElement('a');
a.href = 'data:' + mimeType + ';charset=utf-8,' + escape(data);
a.download = fileName;
a.style = 'display:none';
if (navigator.msSaveBlob) { // IE 10+
var blob = new Blob([data], {
"type": "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, fileName);
}
else { // ELSE non-IE
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
we can also do like this,we can add a return statement,this looks better
var fileName = "test";
var data = $(this).first(); //Only one table
var a = document.createElement('a');
a.href = 'data:' + mimeType + ';charset=utf-8,' + escape(data);
a.download = fileName;
a.style = 'display:none';
if (navigator.msSaveBlob) { // IE 10+
var blob = new Blob([data], {
"type": "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, fileName);
return;
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
I have written json code in string and i want to send it using xmlhttp as .json file. Is it possible to do it with blob?
var cleanScript = {
'type': 'script',
'api_key': api_key,
'data': data,
'inputs': inputs,
'timeoutSeconds': timeoutSeconds
};
var jsonse = JSON.stringify(cleanScript, null, 2);
Now json to blob?
Try something like this
var cleanScript = {
'type': 'script',
'api_key': api_key,
'data': data,
'inputs': inputs,
'timeoutSeconds': timeoutSeconds
};
var jsonse = JSON.stringify(cleanScript);
var blob = new Blob([jsonse], {type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = "backup.json";
a.textContent = "Download backup.json";
document.getElementById('json').appendChild(a);
<div id="json"></div>
Try the code below:
var int2ByteArray = function(i, minByteCount) {
var result = [],
buf = code = +i,
offsetCount = 0;
while ((buf = code>>(8 * offsetCount)) || offsetCount < minByteCount) {
buf = buf & 0xFF;
++offsetCount;
result.push(buf);
}
return result.reverse();
};
var ascii2ByteArray = function(s) {
if (!s) return 0;
var result = [];
[].map.call(s, function(c) {
result = result.concat(int2ByteArray((typeof(c)).toLowerCase() == "number" ? c : c.charCodeAt(0)));
});
return result;
};
// You got the blob here, do whatever you want.
var blob = new Blob(new Uint8Array(ascii2ByteArray(jsonse)), {type:"text/json"});
The matrix is to convert a string(stringfied by JSON.stringify) in to a Uint8Array that could be used making a blob.
I happened make something like that before, hope it's useful.