json2xls
json2xls copied to clipboard
Save on client side file corrupted
From server I am using this to send the file to client.
response.xls('data.xlsx', jsonArr, 'binary');
In client I am using this to download file.
var blob = new Blob([result.data], { //type: 'application/vnd.ms-excel' type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' //type: 'binary' }); var a = document.createElement('a'); var url = URL.createObjectURL(blob); a.href = url; a.download = "sss" //yourfilename a.target = '_blank'; document.body.appendChild(a); a.click();
It downloads the file. But when I open the file, it says corrupt.
Please help.
@sunojvijayan Hi, I am also facing same issue. If you got any solution please share. Thanks
Hi I was not able to do this in one go. So I saved the file to the server and then gave the link to the client side for the user to download.
Hi, after struggling a lot, finally i got the solution. I have followed the below approach :
- convert json to xlsx using json2xls
- write that converted data in file on server.
- then read that file and send that data as arrayBuffer to front-end.
- on front-end, set response type as arrayBuffer and convert that response to blob and save using filesaver or download by creating url(as mentioned @sunojvijayan )
In my case, 'corrupt file' error was shown while i was sending file data before completion of write file method. To resolve this, i write read file code in callback of writeFile function and send that response to front-end.
Hope this will help.
Any efficient solution to this?
We apply the following preprocessing of the data from json2xls before creating the anchor element as per @sunojvijayan code above. const decodeBase64 = (str) => { try { return window.atob(str); } catch (e) { return str; } };
const decoded = decodeBase64(data); const buf = new ArrayBuffer(decoded.length); const view = new Uint8Array(buf); for (let i = 0; i !== decoded.length; ++i) { view[i] = decoded.charCodeAt(i) & 0xFF; }
const blob = new Blob([buf], { type: 'application/octet-stream' });