HTML 링크에서 PDF 파일을 다운로드할 수 있게 만드는 방법은 무엇인가요?

아래와 같이 웹 페이지에서 다운로드할 수 있는 PDF 파일 링크를 제공하고 있습니다.

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

문제는 사용자가 이 링크를 클릭하면 다음과 같은 문제가 발생합니다.

  • 사용자가 Adobe Acrobat을 설치한 경우 Adobe Reader의 동일한 브라우저 창에서 파일이 열립니다.
  • Adobe Acrobat이 설치되어 있지 않은 경우 사용자에게 파일 다운로드 팝업이 표시됩니다.

하지만 'Adobe Acrobat'의 설치 여부에 관계없이 항상 사용자에게 다운로드 팝업이 표시되기를 원합니다.

어떻게 해야 하는지 알려주세요.

그러나 이는 단순한 HTML 5 의 공통 문제입니다 there& # 39 mcds 아는 사람이 거의 없다.

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

여기서 '' 는 사용자의 뉴피렌임 제안됩니다 파일_이름 파일을 저장할. 또는 it 가 있는 경우, 다음과 같은 세르베르사이드 빈 남겨두십시오 기본적으로 파일_이름

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

호환성: 내가 이걸 모두 21, 철, Firefox 좋았소 협력했습니다 테스트되었습니다. 작동하지 않을 것이라고 html5 호환되지 않는 또는 오래된 브라우저. # 39, t 는 힘 있는 유일한 있지만브라우저에 내가 테스트되었습니다 didn& 다운로드하십시오 IE.

호환성에 있습니다. http://caniuse.com/ # 성과 = 다운로드하십시오

해설 (6)
해결책

.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); 

추신: 그리고 파일 확장자 허용 안 함, 슬래시 거부, 값에 .pdf 추가 등 사람들이 파일을 도용하지 못하도록 변수에 대해 몇 가지 건전성 검사를 실행하세요.

해설 (12)

, T # 39 Don& 할말이다 모든 파일을 통해 루프 그 대신 사용하여 가속화합니다. 참고: 윈도우즈에서 동작하지 않습니다. 이는 끕니까 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;
}

일부 php 파일을 다운로드 받을 수 있는지 너회의 살균 가변적입니다 사람이 할 수 있다.

해설 (1)

Php 스크립트를 사용하는 대신 읽고 # 39 의 헤더 파일을 사용하여 더 멋있게 플러시합니다 it& 새로 쓰는 '.htaccess'. 이 새벽꺼정 nice&quot 한 "; URL ('미피레스포드프' 대신 '다운로d.프프? myfile').


ForceType applicaton/octet-stream
Header set Content-Disposition attachment
해설 (3)

내가 plain old 함께 할 수 있는 방법이 있는 HTML 과 JavaScript / jQuery 확연하게 떨어집니다. 테스트를 통해 ie7 10, 사파리, 크롬 · 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 기능을 추가할 수 있다 ' () 의 건네십시오. # 39 감지및 it& 빈다우지오픈 을 사용할 수 있는' 새 창을 열려면 절실해졌습니다.

해설 (0)

Html5 에서 쉽게 알 수 없다. 추가하기에서는 '다운로드' 속성.

대부분의 현대 브라우저를 통해 받을 수 있습니다.

<a download href="file.pdf">Download PDF</a> 
해설 (2)

이것이 핵심입니다:

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

PDF 파일을 보낼 때 콘텐츠 유형 application/x-pdf-document 또는 application/pdf가 전송됩니다. Adobe Reader는 일반적으로 이 MIME 유형에 대한 핸들러를 설정하므로 브라우저는 PDF MIME 유형 중 하나가 수신될 때 문서를 Adobe Reader로 전달합니다.

해설 (0)

저는 준비됐답니다 매우 늦은 답변 이건 찾았다고 해킹 이를 javascript 로.

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



    File Uploader  
    <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;  
        }  



    <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>  

해설 (1)

39 의 here& 다른 외곽진입. 이러한 문제를 해결하기 보다는 내가 포지셔닝하십시오 이용할 수 있는 브라우저 지원, 또는 웹 서버, 애플리케이션 계층에서 사용할 수 없다.

Htaccess 파일 넣을 수 있는 apache 를 사용하는 경우, 아래 코드는 의 관련 디렉터리입니다 사용할 수 있습니다. 물론 이 경우 위험할 수 있다는 것이 아니라, 액세스하도록 httpd. conf 에서 있습니다.


  Header set Content-Disposition attachment

Regex 는 단순히 디렉티브을 필레스 마치 원하는 대로 설정할 수 있도록, 또는 다른 확장명은 따라 세부적으로 추가할 수 있다.

이 같은 일을 할 수 있는 첫 번째 줄로 선 높여줍니까 헤더입니다 PHP 스크립트 명이다. 물론 컨텐츠 유형에 라인을 설정해야 하는 경우 이 같은 방식으로 할 수 있지만, 그래서 내가 haven& # 39, t 필요한 것으로 나타났다.

해설 (0)

이거 드세요.

'a href = = = http://myurl.com/mypath/&quot 파일 경로를 pdf_server_with_path.php &quot <;;;; 내 eBook&lt /a&gt 다운로드하십시오 &gt pdffilename&amp?;;'

코드 δ1 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);
해설 (0)

내가 해결 내거냐 전체 url 을 사용하여 PDF 파일 (넣는 게 아니라 파일 이름이나 위치로 href): a href = &quot, 도메인. com/pdf/filename.pdf&quot.

해설 (0)

다운로드 속도 제한 할 경우, 이 코드를 사용하여!!

<?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!');
}

?>

자세한 내용은 여기를 클릭

해설 (0)

Ruby on Rails 애플리케이션(특히 Prawn 젬 및 Prawnto Rails 플러그인 같은 것을 사용하는 경우)에서는 이전 PHP 예제처럼 전체 스크립트를 사용하는 것보다 조금 더 간단하게 이 작업을 수행할 수 있습니다.

컨트롤러에서:

def index

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

렌더:레이아웃 => 거짓 부분은 브라우저에 PDF 렌더링을 시도하는 대신 "이 파일을 다운로드하시겠습니까?"라는 프롬프트를 열도록 지시합니다. 그러면 정상적으로 파일에 링크할 수 있습니다(http://mysite.com/myawesomepdf.pdf).

해설 (3)