簡體   English   中英

從服務器下載帶有角度$ http.get的文件

[英]Download file from server with angular $http.get

我試圖在用戶單擊“下載PDF”按鈕時觸發文件下載。 對該API進行調用,並進行一些檢查,然后返回文件。 我不想在瀏覽器中打開文件。 我已經閱讀了很多關於如何執行此操作的stackoverflow問題,但無法使其正常工作。 我以文本形式獲取文件內容,但是瀏覽器沒有保存文件,也沒有給我選擇將其保存為文件的選擇。

這就是我所擁有的。

HTML

<button ng-click="apiDownload()">Download PDF</button>

AngularJS控制器

$scope.apiDownload = function(){
    var config = {
        method: 'GET',
        url: "/api/download",
        headers: {
            'Accept': 'application/pdf'
        }
    };
    $http(config)
        .success(function(res){
            console.log(res);
        })
        .error(function(res){});
};

PHP API (大部分來自此處

function apiDownloadFile() {
    $file_name = "download/test.pdf";
    $abs_file_name = realpath(dirname(__FILE__)).'/'.$file_name;
    if(is_file($abs_file_name) && file_exists($abs_file_name)) {

        // required for IE
        if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }

        // get the file mime type using the file extension
        switch(strtolower(substr(strrchr($file_name, '.'), 1))) {
            case 'pdf': $mime = 'application/pdf'; break;
            case 'zip': $mime = 'application/zip'; break;
            case 'jpeg':
            case 'jpg': $mime = 'image/jpg'; break;
            default: $mime = 'application/force-download';
        }
        header('Pragma: public');   // required
        header('Expires: 0');       // no cache
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($abs_file_name)).' GMT');
        header('Cache-Control: private',false);
        header('Content-Type: '.$mime);
        header('Content-Disposition: attachment; filename='.basename($abs_file_name));
        header('Content-Transfer-Encoding: binary');
        header('Content-Length: '.filesize($abs_file_name));    // provide file size
        header('Connection: close');
        readfile($abs_file_name);       // push it out
        exit();
    }

}

我在chrome開發人員工具中看到了這些標頭:

請求標題

GET /api/download HTTP/1.1
Host: sa.dev
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Accept: application/pdf
If-Modified-Since: 0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36
Referer: https://sa.dev/insights
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,da;q=0.6,sv;q=0.4,no;q=0.2,nb;q=0.2
Cookie: ...

響應標題

HTTP/1.1 200 OK
Date: Mon, 16 Mar 2015 14:27:08 GMT
Server: Apache/2.4.9 (Unix) PHP/5.6.5 OpenSSL/0.9.8zc
X-Powered-By: PHP/5.6.5
Pragma: public
Expires: 0
Cache-Control: must-revalidate, post-check=0, pre-check=0
Last-Modified: Mon, 16 Mar 2015 09:04:06 GMT
Cache-Control: private
Content-Disposition: attachment; filename=test.pdf
Content-Transfer-Encoding: binary
Content-Length: 5501633
Connection: close
Content-Type: application/pdf

我通過使用John CulvinerjQuery.fileDownload庫解決了此問題(請參閱此SO-answer )。

使用jQuery.fileDownload時,我必須在代碼中添加兩件事。

  1. 設置一個cookie

    • 在PHP中: setcookie('fileDownload', "true", NULL, '/');
    • Set-Cookie標頭將如下所示: Set-Cookie: fileDownload=true; path=/ Set-Cookie: fileDownload=true; path=/
  2. 調用$.fileDownload('/api/download'); 來自js。 並刪除有角的$ http。

有關如何使用jQuery.fileDownload的更多信息,請參見此博客

如果有人有解決方案而不使用jQuery庫,請隨時將其發布為答案。

$scope.apiDownload = function(){
    window.open('api/download');
};

很棒

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM