簡體   English   中英

如何使 PDF 文件可在 HTML 鏈接中下載?

[英]How to make PDF file downloadable in HTML link?

我在我的網頁上提供 pdf 文件的鏈接以供下載,如下所示

<a href="myfile.pdf">Download Brochure</a>

問題是當用戶點擊這個鏈接時

  • 如果用戶已安裝 Adob​​e Acrobat,則它會在 Adob​​e Reader 的同一瀏覽器窗口中打開文件。
  • 如果未安裝 Adob​​e Acrobat,則會向用戶彈出下載文件。

但我希望它總是彈出給用戶下載,無論是否安裝了“Adobe acrobat”。

請告訴我我該怎么做?

這是一個常見問題,但很少有人知道有一個簡單的 HTML 5 解決方案:

<a href="./directory/yourfile.pdf" download="newfilename">Download the pdf</a>

其中newfilename是用戶保存文件的建議文件名。 或者如果您將其留空,它將默認為服務器端的文件名,如下所示:

<a href="./directory/yourfile.pdf" download>Download the pdf</a>

兼容性:我在 Firefox 21 和 Iron 上對此進行了測試,兩者都運行良好。 它可能不適用於與 HTML5 不兼容或過時的瀏覽器。 我測試過的唯一沒有強制下載的瀏覽器是 IE...

在此處檢查兼容性: http : //caniuse.com/#feat=download

與其鏈接到 .PDF 文件,不如執行類似的操作

<a href="pdf_server.php?file=pdffilename">Download my eBook</a>

它輸出自定義標題,打開 PDF(二進制安全)並將數據打印到用戶的瀏覽器,然后他們可以選擇保存 PDF,而不管他們的瀏覽器設置。 pdf_server.php 應如下所示:

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));   
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
} 
fclose($fp); 

PS:顯然對“文件”變量運行一些健全性檢查以防止人們竊取您的文件,例如不接受文件擴展名,拒絕斜杠,將 .pdf 添加到值中

不要遍歷每個文件行。 改用readfile ,它更快。 這是 php 站點: http : //php.net/manual/en/function.readfile.php

$file = $_GET["file"];
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header("Content-Type: application/force-download");
    header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
    // header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}

確保清理你的 get 變量,因為有人可以下載一些 php 文件......

使用.htaccess重寫頭文件而不是使用 PHP 腳本來讀取和刷新文件。 這將保留一個“不錯”的 URL( myfile.pdf而不是download.php?myfile )。

<FilesMatch "\.pdf$">
ForceType applicaton/octet-stream
Header set Content-Disposition attachment
</FilesMatch>

我找到了一種使用普通舊 HTML 和 JavaScript/jQuery 優雅降級的方法。 在 IE7-10、Safari、Chrome 和 FF 中測試:

下載鏈接的 HTML:

<p>Thanks for downloading! If your download doesn't start shortly, 
<a id="downloadLink" href="...yourpdf.pdf" target="_blank" 
type="application/octet-stream" download="yourpdf.pdf">click here</a>.</p>

jQuery(純 JavaScript 代碼會更冗長)模擬在一小段延遲后點擊鏈接:

var delay = 3000;
window.setTimeout(function(){$('#downloadLink')[0].click();},delay);

為了使其更健壯,您可以添加 HTML5 功能檢測,如果不存在,則使用window.open()打開一個包含該文件的新窗口。

這是關鍵:

header("Content-Type: application/octet-stream");

內容類型 application/x-pdf-document 或 application/pdf 在發送 PDF 文件時發送。 Adobe Reader 通常會為此 MIME 類型設置處理程序,因此當接收到任何 PDF MIME 類型時,瀏覽器會將文檔傳遞給 Adob​​e Reader。

HTML5中有一種更簡單的方法:添加Download屬性。

大多數現代瀏覽器都支持它。

<a download href="file.pdf">Download PDF</a> 

我知道我回答這個問題已經很晚了,但我發現了一個在 javascript 中做到這一點的技巧。

function downloadFile(src){
    var link=document.createElement('a');
    document.body.appendChild(link);
    link.href= src;
    link.download = '';
    link.click();
}

這可以使用 HTML 來實現。

<a href="myfile.pdf">Download Brochure</a>

添加下載屬性:這里的文件名將是 myfile.pdf

<a href="myfile.pdf" download>Download Brochure</a>

為下載屬性指定一個值:

<a href="myfile.pdf" download="Brochure">Download Brochure</a>

這里的文件名將是 Brochure.pdf

試試這個:

<a href="pdf_server_with_path.php?file=pdffilename&path=http://myurl.com/mypath/">Download my eBook</a>

pdf_server_with_path.php 里面的代碼是:

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".pdf";
$path = $_GET["path"];
$fullfile = $path.$file;

header("Content-Disposition: attachment; filename=" . Urlencode($file));   
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . Filesize($fullfile));
flush(); // this doesn't really matter.
$fp = fopen($fullfile, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
} 
fclose($fp);

這是一種不同的方法。 我更喜歡使用 Web 服務器邏輯而不是依賴瀏覽器支持或在應用程序層解決這個問題。

如果您使用的是 Apache,並且可以將 .htaccess 文件放在相關目錄中,則可以使用以下代碼。 當然,如果您可以訪問它,您也可以將它放在 httpd.conf 中。

<FilesMatch "\.(?i:pdf)$">
  Header set Content-Disposition attachment
</FilesMatch>

FilesMatch 指令只是一個正則表達式,因此可以根據需要進行精細設置,或者您可以添加其他擴展名。

Header 行與上述 PHP 腳本中的第一行執行相同的操作。 如果您還需要設置 Content-Type 行,您可以以相同的方式進行設置,但我認為沒有必要這樣做。

我使用 PDF 文件的整個 url 解決了我的問題(而不僅僅是將文件名或位置放在 href 中):a href="domain . com/pdf/filename.pdf"

如果您需要限制下載速率,請使用此代碼!

<?php
$local_file = 'file.zip';
$download_file = 'name.zip';

// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file))
{
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($local_file));
header('Content-Disposition: filename='.$download_file);

flush();
$file = fopen($local_file, "r");
while(!feof($file))
{
    // send the current file part to the browser
    print fread($file, round($download_rate * 1024));
    // flush the content to the browser
    flush();
    // sleep one second
    sleep(1);
}
fclose($file);}
else {
die('Error: The file '.$local_file.' does not exist!');
}

?>

欲了解更多信息,請單擊此處

<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
    <title>File Uploader</title>  
    <script src="../Script/angular1.3.8.js"></script>  
    <script src="../Script/angular-route.js"></script>  
    <script src="../UserScript/MyApp.js"></script>  
    <script src="../UserScript/FileUploder.js"></script>  
    <>  
        .percent {  
            position: absolute;  
            width: 300px;  
            height: 14px;  
            z-index: 1;  
            text-align: center;  
            font-size: 0.8em;  
            color: white;  
        }  

        .progress-bar {  
            width: 300px;  
            height: 14px;  
            border-radius: 10px;  
            border: 1px solid #CCC;  
            background-image: -webkit-gradient(linear, left top, left bottom, from(#6666cc), to(#4b4b95));  
            border-image: initial;  
        }  

        .uploaded {  
            padding: 0;  
            height: 14px;  
            border-radius: 10px;  
            background-image: -webkit-gradient(linear, left top, left bottom, from(#66cc00), to(#4b9500));  
            border-image: initial;  
        }  
    </>  
</head>  
<body ng-app="MyApp" ng-controller="FileUploder">  
    <div>  
        <table ="width:100%;border:solid;">  
            <tr>  
                <td>Select File</td>  
                <td>  
                    <input type="file" ng-model-instant id="fileToUpload" onchange="angular.element(this).scope().setFiles(this)" />  
                </td>  
            </tr>  
            <tr>  
                <td>File Size</td>  
                <td>  
                    <div ng-repeat="file in files.slice(0)">  
                        <span ng-switch="file.size > 1024*1024">  
                            <span ng-switch-when="true">{{file.size / 1024 / 1024 | number:2}} MB</span>  
                            <span ng-switch-default>{{file.size / 1024 | number:2}} kB</span>  
                        </span>  
                    </div>  
                </td>  
            </tr>             
            <tr>  
                <td>  
                    File Attach Status  
                </td>  
                <td>{{AttachStatus}}</td>  
            </tr>  
            <tr>  
                <td>  
                    <input type="button" value="Upload" ng-click="fnUpload();" />  
                </td>  
                <td>  
                    <input type="button" value="DownLoad" ng-click="fnDownLoad();" />  
                </td>  
            </tr>  
        </table>  
    </div>  
</body>  
</html>   

在 Ruby on Rails 應用程序中(尤其是使用 Prawn gem 和 Prawnto Rails 插件),您可以比完整的腳本(如前面的 PHP 示例)更簡單地完成此操作。

在您的控制器中:

def index

 respond_to do |format|
   format.html # Your HTML view
   format.pdf { render :layout => false }
 end
end

render :layout => false 部分告訴瀏覽器打開“你想下載這個文件嗎?” 提示而不是嘗試呈現 PDF。 然后您就可以正常鏈接到該文件: http : //mysite.com/myawesomepdf.pdf

暫無
暫無

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

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