dougekui1518 2018-09-26 15:25
浏览 635
已采纳

使用Axios获取并保存Excel文件

I am using react and axios to do a POST to a php service that will return a .xlsx file. The .xlsx file is created properly on the server, but during transit back it gets corrupted, through the Chrome inspector the data seems to be getting converted to a string and many characters are getting changed as a result. Is there a way to do this? Things I have tried:

Headers on request

'Accept': 'application/octet-stream',
'responseType': 'blob',

With the response object

fileDownload(new Blob([response.data]), 'report.xlsx');

Alternatively with the response object

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

No matter what I try it seems to be getting corrupted. On the server side I have the following PHP code:

$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;
  • 写回答

2条回答 默认 最新

  • dongtaidai0492 2018-09-26 15:38
    关注

    Try removing responseType from the headers and add it directly into your options object that you pass into axios:

    axios({
        method:'GET',
        url: '[your_url_to_get_file]',      
        responseType: 'blob', 
        headers: { your headers }
    })
    

    On top of that, I would try using application/vnd.openxmlformats-officedocument.spreadsheetml.sheet as your content-type, instead of octect-stream. I've never tried octect-stream but the one I mentioned has always worked for me with .xlsx files.

    For reference about MIME types see here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题