json2xls icon indicating copy to clipboard operation
json2xls copied to clipboard

Save on client side file corrupted

Open sunojvijayan opened this issue 7 years ago • 5 comments

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 avatar Jan 05 '18 01:01 sunojvijayan

@sunojvijayan Hi, I am also facing same issue. If you got any solution please share. Thanks

PundirKajal avatar Jan 29 '18 03:01 PundirKajal

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.

sunojvijayan avatar Jan 29 '18 12:01 sunojvijayan

Hi, after struggling a lot, finally i got the solution. I have followed the below approach :

  1. convert json to xlsx using json2xls
  2. write that converted data in file on server.
  3. then read that file and send that data as arrayBuffer to front-end.
  4. 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.

PundirKajal avatar Feb 05 '18 00:02 PundirKajal

Any efficient solution to this?

ghost avatar Nov 27 '18 06:11 ghost

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' });

ge-hall avatar Dec 19 '18 07:12 ge-hall