从外部API下载XLS文件

问题描述 投票:0回答:1

当我发出 GET 请求时,我的外部 API 返回以下内容:

"PK\u0003\u0004\n\u0000\u0000\u0000\u0008\u0000f��T���\tY\u0001\u0000\u0000�\u0004\u0000\u0000\u0013\u0000\u0000\u0000[Content_Types].xml��Mn�0\u0010��=E�-J\u000c]TUE¢��\u0016��\u0000�xB,\u001c���w\u0012(�* �`\u0013+�7�{��\u0019O��I�\u0018H;��Q6\u0014\t��)m\u0017������\"�\u0008V�q\u0016s�C\u0012��n<�y���-墎�?IIe�\rP�<Z�T.4\u0010�6,��r\t\u000b����,��hc\u001a[\u000fQ��X����eˏ�A\u0002\u001a\u0012��^زr\u0001�\u001b]B�\\[���\u001e\u0008\u0019wv\u001a���\u0001\u000b�<Ih+�\u0001��w�L�\n�\u0019��\u0006\r���ȍ\u000b�/…u0000f��T�v�^_\u0001\u0000\u0000�\u0002\u0000\u0000\u0011\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000�\u0012\u0000\u0000docProps/core.xmlPK\u0001\u0002\u0014\u0000\n\u0000\u0000\u0000\u0008\u0000f��T�\u0005s>[\u0001\u0000\u0000r\u0002\u0000\u0000\u000f\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000e\u0014\u0000\u0000xl/workbook.xmlPK\u0005\u0006\u0000\u0000\u0000\u0000\u0010\u0000\u0010\u0000�\u0003\u0000\u0000�\u0015\u0000\u0000\u0000\u0000"

这应该是我的 XLS 文件。 目前我用axios处理如下:

  ...then(response => {
    const url = window.URL.createObjectURL(new Blob([response.data.result]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `EventID-${response.data.result.eventId}_${dateFormat(Date.now(), 'dd-mmm-yyyy')}.xls`);
    document.body.appendChild(link);
    link.click();
  }, errorHandler);

尽管这会返回一个带有 [Object object] 列的 Excel 文件。 如何将响应转换为正确的 Excel 文件?

reactjs excel api download next.js
1个回答
0
投票

这是我的代码示例供您参考:

在我的 Next.js 应用程序中,服务器端页面无法将 blob 对象从服务器传输到客户端。

因此,我通过使用名为 download-button.tsx 的组件解决了这个问题,该组件用于下载 Excel 文件。

组件/下载按钮.tsx

async function download() {
  window.location.href = '/api/download';
}

<Button onClick={() => download()}>Download</Button>

api/download/route.ts

export async function GET(req: Request) {
  const requestUrl = `${apiBaseUrl}/path`;
        
  const fetchResponse = await fetch(requestUrl, {
   method: 'GET',
   headers: {
    Authorization: `Bearer ${accessToken}`,
   },
  });
        
  return new Response(fetchResponse.body, {
   headers: {
   ...fetchResponse.headers,
   'content-disposition': `attachment; filename="filename.xlsx"`,
   },
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.