首页 > 解决方案 > 为什么下载的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();
}

标签: javascriptphpms-office

解决方案


推荐阅读