簡體   English   中英

如何從 ArrayBuffer 中的服務器保存.xlsx 文件?

[英]How to save .xlsx file from server from ArrayBuffer?

我有一個 XLSX,我從 nodejs 服務器作為 ArrayBuffer 發送。

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

我在 axios 中收到它,並帶有以下參數:

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"}

我嘗試像這樣下載它:

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

但是 xlsx 文件最終損壞了。 將 data.xlsx 更改為 data.csv 給了我一行整數。 當我在客戶端打印出來時,數組最終看起來像這樣。

[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]

而在服務器端,它以十六進制值表示。

<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>

是編碼問題嗎? 如何在客戶端將緩沖區轉換為 utf8?

所以我意識到不知何故,數據是作為數組而不是數組緩沖區接收的。 我通過將數組轉換為 ArrayBuffer 來解決這個問題:

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

然后像這樣使用它:

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

我最近也遇到了同樣類型的問題,我嘗試了下面的代碼片段。 它對我有用。

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();

謝謝你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM