使用 Axios 获取并保存 Excel 文件

Mik*_*e B 3 php reactjs axios

我正在使用 react 和 axios 对将返回 .xlsx 文件的 php 服务执行 POST。.xlsx 文件在服务器上正确创建,但在返回过程中它被损坏,通过 Chrome 检查器,数据似乎被转换为字符串,结果许多字符被更改。有没有办法做到这一点?我尝试过的事情:

应要求提供标题

'Accept': 'application/octet-stream',
'responseType': 'blob',
Run Code Online (Sandbox Code Playgroud)

与响应对象

fileDownload(new Blob([response.data]), 'report.xlsx');
Run Code Online (Sandbox Code Playgroud)

或者使用响应对象

const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.xlsx');
link.click();
Run Code Online (Sandbox Code Playgroud)

无论我尝试什么,它似乎都已损坏。在服务器端,我有以下 PHP 代码:

$response = new Stream();
$response->setStream(fopen($tempFilePath, 'r'));
$response->setStatusCode(200);
$response->setStreamName($tempFilePath);
$responseHeaders = new Headers();
$responseHeaders->addHeaders(array(
    'Content-Disposition' => 'attachment; filename='report.xlsx',
    'Content-Type' => 'application/octet-stream',
    'Content-Length' => filesize($tempFilePath),
    'Expires' => '@0', 
    'Cache-Control' => 'must-revalidate',
    'Pragma' => 'public'
));
$response->setHeaders($responseHeaders);
return $response;
Run Code Online (Sandbox Code Playgroud)

Obj*_*rix 7

const axios = require('axios');
const fs = require('fs');

const getXLS = () => {
    return axios.request({
    responseType: 'arraybuffer',
    url: 'https://drive.google.com/ft7P9FAQ/view?usp=sharing',
    method: 'get',
    headers: {
    'Content-Type': 'blob',
    },
  }).then((result) => {
      const outputFilename = 'xyzzzz.xls';
      fs.writeFileSync(outputFilename, result.data);
      return outputFilename;
    });
  }

  getXLS();
Run Code Online (Sandbox Code Playgroud)


小智 5

尝试responseType从标题中删除并将其直接添加到您传递给 axios 的选项对象中:

axios({
    method:'GET',
    url: '[your_url_to_get_file]',      
    responseType: 'blob', 
    headers: { your headers }
})
Run Code Online (Sandbox Code Playgroud)

最重要的是,我会尝试使用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet作为您的内容类型,而不是octect-stream. 我从未尝试过,octect-stream但我提到的那个总是对我有用 .xlsx 文件。

有关 MIME 类型的参考,请参见此处