javascript - 为什么下载的excel文件“损坏”
问题描述
我正在开发一个下载由 api 生成的 excel 报告的 Web 应用程序。在邮递员中运行调用会返回一个打开时没有问题的文件。通过 Web 应用程序下载文件已损坏,Excel 无法修复它。如果我在记事本 ++ 中打开无法修复的损坏文件并保存它而不进行任何更改,它现在已损坏但可以由 Excel 修复。最重要的是,根据十六进制编辑器,所有三个文件都是相同的。
编辑:我无权访问生成 excel 的 API,所以我无法提供该代码。出于调试目的,我在服务器上使用了一个文件,并且发生了同样的问题,所以它似乎在我身边的某个地方。中间api函数是
function exportDebuggy($request, $fileSource)
{
$resData = array(
"success" => false,
"response" => array(),
"message" => ""
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fileSource);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_ENCODING , "");
curl_setopt($ch, CURLOPT_HEADER, false);
$data = curl_exec($ch);
$err = curl_error($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($err)
{
$resData['message'] = "cURL Error #:" . $err;
}
else if( $code === 401 )
{
$resData['message'] = "Client session has expired. Please re login.";
}
else
{
$resData = "";
}
return $resData;
}
进行调用并处理保存的js代码是
function exportDebuggy()
{
var xmlhttp = new XMLHttpRequest();
var endpoint = "/wp-json/data-tracker/exportDebug";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200)
{
var data = window.URL.createObjectURL(xmlhttp.response);
var link = document.createElement('a');
link.href = data;
link.download="transactionsDownloaded.xlsx";
link.click();
}
else if (xmlhttp.status == 400)
{
alert('There was an error 400');
}
else
{
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", endpoint, true);
xmlhttp.setRequestHeader( 'X-WP-Nonce', userID );
xmlhttp.responseType = "blob";
xmlhttp.send();
}
解决方案
推荐阅读
- python - Python & Sqlalchemy - 连接模式 -> 随机断开与远程服务器的连接
- javascript - 使用 window.open 在 Chrome 中打开一个具有所有功能(菜单栏等)的新窗口(不是选项卡)
- wordpress - Fedora 上 Wordpress 中的永久链接损坏
- vuejs2 - vuejs - 异步和动态组件
- php - PHP Rabbit MQ 从单个队列中读取特定消息
- javascript - 从字符串打印 vue 组件
- ios - 对于 alertController:UISegmentedControl 中选定段的 sourceView 是什么
- javascript - Winston 详细记录器未同时登录文件和控制台
- reactjs - 将数据从功能组件传递到 app.js
- solr - 使用 nutch 中的 solrindexing 作业查找 solr 中已存在文档的数量