2015-12-16 87 views
0

我已经在SO中找到manyquestionshere关于这个主题,但是它们中的任何一个都可以帮助我解决特定的问题。使用JQuery AJAX和PHP下载PDF文件

我需要发送一个ajax请求到PHP,然后下载一个PDF文件。

这是我的Javascript

$('body').on("click",'.download-file', function(e) { 
     e.stopPropagation(); 
     var id = $(this).attr('data-id'); 
      $.ajax({ 
       url: 'app/myPage/download',// The framework will redirect it to index.php and then to myPage.class and method dowload 
       data: id, 
       type: 'POST', 
       success: function (return) { 
        console.log(return); 
       }, 
       error: function(jqXHR, textStatus, errorThrown) { 
        console.log("Error... " + textStatus + "  " + errorThrown); 
       } 
      }); 
    }); 

这是我的PHP文件:

class myPage{ 
    public function download() 
     { 
      $id = $_POST['id']; 
      $filePath = $this->methodToGetFile($id); 
      $name = end(explode('/',$filePath)); 
      $fp = fopen($filePath, 'rb'); 
      header("Cache-Control: "); 
      header("Pragma: "); 
      header("Content-Type: application/octet-stream"); 
      header("Content-Length: " . filesize($filePath)); 
      header("Content-Disposition: attachment; filename='".$name."';"); 
      header("Content-Transfer-Encoding: binary\n"); 
      fpassthru($fp); 
      exit; 
    } 
} 

通过这种方法,我在控制台中的PDF “印” 像

%PDF-1.5%����1 0 obj<</Type/Catalog/Pages 2 0 R/Lang(pt-BR) /StructTreeRoot 8 0 R/MarkInfo<</Marked true>>>> ...

所以,我想知道该怎么做才能打开这个文件并下载它。

在链接的问题我看到一些关于window.location,但我不知道如何使用它。

我已经试过改变PHP头来尝试强制下载,但没有成功。在这些情况下,我只收到空的JavaScript没有任何反应。这里是修改的标题:

header('Content-Type: application/pdf');//tried with this option 
    //header('Content-Type: application/octet-stream');// also tried with this other option 
    header('Content-Disposition: attachment; filename=' . $name); 
    header('Content-Transfer-Encoding: binary'); 
    header('Connection: Keep-Alive'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize($filePath)); 

是否有一些很好的方法来做到这一点?

+1

header('Content-Type:application/pdf');而不是标题('Content-Type:application/octet-stream'); – Ophitect

+0

我已经试过了。 – James

+1

header('Content-type:application/pdf');你有一个小字母t? – Ophitect

回答

1

我不认为这种方法来下载pdf将工作。 Javascript正在发送请求,并且php正在发送响应。您希望将响应直接发送到浏览器,而不是JavaScript。您应该更改下载链接以直接转至下载位置。不需要ajax/javascript。像这样:

<a href="javascript:void(0)" onclick = "window.href='app/myPage/download?'+id">download</a>