简体   繁体   中英

How to save .xlsx file from server from ArrayBuffer?

I have an XLSX that I'm sending from a nodejs server as an ArrayBuffer.

const result = nodeExcel.execute(data);
const body = Buffer.from(result, 'binary');

I receive it in axios with these paramaters:

responseType: arraybuffer
headers: {"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"}

I try to download it like this:

const buftype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8';
const url = window.URL.createObjectURL(new Blob([res.data]), {
   type: buftype
});
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'data.xlsx');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

But the xlsx file ends up corrupt. Changing data.xlsx to data.csv gives me a single row of integers. The array ends up looking like this when I print it out on the client side.

[80, 75, 3, 4, 10, 0, 0, 0, 8, 0, 252, 113, 209, 80, 120, 168, 205, 70, 60, 1, 0, 0, 180, 4, 0, 0, 19, 0, 0, 0, 91, 67, 111, 110, 116, 101, 110, 116, 95, 84, 121, 112, 101, 115, 93, 46, 120, 109, 108, 173, 148, 221, 78, 2, 49, 16, 133, 95, 101, 211, 91, 179, 91, 240, 194, 24, 195, 194, 133, 122, 171, 36, 250, 2, 181, 157, 101, 27, 250, 151, 206, 128, 240, 246, 14, 197, 160, 65, 3, 10, 220, 108, 179, 157, 51, 231, 59, 253, 73, 71]

while on the server side, it's represented in hex values.

<Buffer 50 4b 03 04 0a 00 00 00 08 00 fc 71 d1 50 78 a8 cd 46 3c 01 00 00 b4 04 00 00 13 00 00 00 5b 43 6f 6e>

Is it the encoding that's the problem? How do I turn the buffer into utf8 on the client side?

So I realized that somehow, the data is being received as an array instead of arraybuffer. I fixed this by converting the array into an ArrayBuffer with this:

a2ab(s) {
    let buf = new Uint8Array(s).buffer;
    return buf;
},

Then using it like this:

let buf = this.a2ab(res.data);
const buftype = 'application/vnd.ms-excel;charset=utf-8';
let blob = new Blob([buf], {
    type: buftype
});

I also faced same type of issue recently, I tried below snippet. It worked for me.

const res = await axios.get("url-here", {
  { responseType: "arraybuffer", headers: { "Content-Type": "blob" } }
});

const fileURL = url.createObjectURL(new Blob([res.data]));
const link = document.createElement("a");
link.href = fileURL;
link.setAttribute("download", "filename.xls");
document.body.appendChild(link);
link.click();

Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM