[英]Why is 'xlsx' used with 'file-saver' to download excel?
[英]xlsx file corrupted while downloading with the file-saver npm package
我在下載xlsx
文件時遇到問題。 我的 excel 文件是用js-xlsx生成的。 我必須添加一些授權標頭來驗證服務器上的傳入請求。 因此,我不能簡單地從客戶端在新窗口中打開鏈接。 出於測試目的,我嘗試通過直接點擊我的 API 端點的瀏覽器鏈接來下載文件(當然是通過臨時刪除授權中間件)。 瀏覽器下載文件沒有任何問題或損壞。 不幸的是,通過axios get 請求使用filesaver.js時,客戶端下載功能並非如此。
我發送響應的后端代碼片段是:
//..... Some code for writing the workBook
const workBookOutput = xlsx.write(workBook, {
bookType: 'xlsx',
type: 'buffer'
});
const xlsxFileBuffer = Buffer.from(workBookOutput);
// res is express HTTP response object
res.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.set('Content-Disposition', 'attachment; filename=excel-export.xlsx');
res.status(200).send(xlsxFileBuffer);
我的客戶端代碼的一部分是:
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json'
};
// here I add some real jwt token in my code, not the dummy that I have below
headers.authorization = `bearer asklndashduwkhd2oo832uejh32oihjdoasincas`;
const options = {
'get',
'https://myURLToAPi/api',
headers,
responseType: 'arraybuffer'
}
const response = await axios(options);
//fileSaver is required above in file
fileSaver.saveAs(
new Blob([response.data], {
type:
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}),
'excel.xlsx'
);
我仍然只得到損壞的文件。 我在服務器端和客戶端都嘗試了多個選項,但是,下載的文件總是損壞。 在獲得我的workbookOutput
后,我嘗試不制作另一個Buffer.from
仍然沒有任何變化。 有人可以在這方面幫助我嗎? 我錯過了什么嗎?
這是我嘗試打開下載損壞后得到的圖片。
我有一個類似的問題 - 我在 Django 中生成 Excel,獲取字節然后使用 Axios 查詢它。 使用 FileSaver 生成的 Excel 已損壞,並且就像 @Seeker 提到的那樣,它的大小是原來的兩倍。
但是,在 Postman 中進行測試時,我可以獲得一個普通文件。 什么解決了我的問題是設置
responseType: 'blob'
在 axios 選項中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.