下载pdf文件slim php



我有以下服务来下载pdf文件:

$app->options('/docDownload',function(){}); // This one just so you can accept OPTIONS
$app->get('/docDownload', function () use ($app){
    $path = "working.pdf";
    $res = $app->response();
    $res['Content-Description'] = 'File Transfer';
    $res['Content-Type'] = 'application/octet-stream';
    $res['Content-Disposition'] ='attachment; filename=' . basename($path);
    $res['Content-Transfer-Encoding'] = 'binary';
    $res['Expires'] = '0';
    $res['Cache-Control'] = 'must-revalidate';
    $res['Pragma'] = 'public';
    $res['Content-Length'] = filesize($path);
    readfile($path);
});

然而,当我运行服务时,我得到以下响应:

%PDF-1.5

%����10 obj& lt;>>>endobj20 obj& lt;>endobj30对象& lt;>/ExtGState<>/ProcSet [/PDF/Text/ImageB/ImageC/ImageI]>>/MediaBox[0 0 595.32 841.92]/Contents 4 0 R/Group<>/Tabs/S/StructParents 0>>endobj4 0对象& lt;>流x ' ' Kk ' ' 0 ' ' ' j ' ' ' |�� �@����J�C M!��$��bA,�ш]T�h�j��V0]���r���0��8R0L.F����70�3�}�8�08L�V�Q��+�')��g��U;��V ��8�o�����o��Ip�I}�W_�r}��N'mգU��g>Ö�Ӎ���n>�D��.�-����<H ' ' ABC ' ' ' ' = ' ' ٻXwc ' z ' ' wx 'endstreamendobj50 obj& lt;>endobj60 obj& lt;>endobj70 obj& lt;>endobj80对象…

要打开pdf,我需要点击响应链接上的第二个鼠标按钮:

WS url

并选择在新选项卡中打开PDF文件,似乎你运行了两次服务来获得PDF文件一次。

我想在每次向WS请求时自动打开pdf文件。

这意味着每次您请求WS,这应该返回在屏幕上直接打开的pdf文件。

谁能帮我修一下吗?

谢谢

也许你需要使用正确的MIME类型,试试这个

$res['Content-Type'] = 'application/pdf';

解决方案可能是不使用AJAX调用下载文件(看起来您正在使用这种方式)。你的页面下载页面应该是这样的:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var PDF_DOWNLOAD_URL = "{{ urlFor('PDFDownload') }}";
$(function(){
    //Your old way
    $("button.download-file").click(function(){
        $.ajax({
            method: "GET",
            url: PDF_DOWNLOAD_URL,
            headers: { 'x-my-custom-header': 'some value' },
            success: function(data){
                console.log("Data received:", data);
            }
        });
    });
});
</script>
</head>
<body>
<button type="button" class="download-file">Download the document</button>
</body>
</html>

你的路由应该这样定义一个名称:

$app->get('/docDownload', function () use ($app){
    $path = "working.pdf";
    $res = $app->response();
    $res['Content-Description'] = 'File Transfer';
    $res['Content-Type'] = 'application/json';
    $res['Content-Transfer-Encoding'] = 'binary';
    $res['Expires'] = '0';
    $res['Cache-Control'] = 'must-revalidate';
    $res['Pragma'] = 'public';
    $fileData = file_get_contents($path);
    $base64 = base64_encode($fileData);
    $response = array();
    $response['pdf'] = $base64;
    $response['customKey'] = "My Custom Value";
    echo json_encode($response);
})->name("PDFDownload");

最新更新