HTML 링크에서 PDF 파일을 다운로드 할 수있게 만드는 방법은 무엇입니까?
아래처럼 웹 페이지에 pdf 파일의 링크를 다운로드 용으로 제공합니다
<a href="myfile.pdf">Download Brochure</a>
문제는 사용자가이 링크를 클릭하면
- 사용자가 Adobe Acrobat을 설치 한 경우 Adobe Reader의 동일한 브라우저 창에서 파일을 엽니 다.
- Adobe Acrobat이 설치되어 있지 않으면 파일 다운로드를 위해 사용자에게 팝업됩니다.
그러나 "Adobe acrobat"의 설치 여부에 관계없이 항상 다운로드를 위해 사용자에게 팝업을 표시하고 싶습니다.
어떻게하면되는지 알려주세요.
.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를 값에 추가하는 것과 같이 사람들이 파일을 훔치는 것을 방지하기 위해 "file"변수에 대해 위생 검사를 실행하십시오.
이것은 일반적인 문제이지만 간단한 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
모든 파일 라인을 반복하지 마십시오 . 더 빠른 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;
}
누군가가 일부 PHP 파일을 다운로드 할 수 있으므로 get 변수를 삭제하십시오 ...
PHP 스크립트를 사용하는 대신 파일을 읽고 플러시하려면을 사용하여 헤더를 다시 작성하는 것이 더 깔끔합니다 .htaccess
. 이렇게하면 " myfile.pdf
대신 "좋은 "URL이 유지됩니다 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 기능 감지를 추가 할 수 있습니다. HTML5 기능 감지 기능이 없으면이를 사용 window.open()
하여 파일로 새 창을 엽니 다.
HTML5에는 더 쉬운 방법이 있습니다 : Download
속성 추가 .
대부분의 최신 브라우저에서 지원됩니다.
<a download href="file.pdf">Download PDF</a>
이것이 핵심입니다 :
header("Content-Type: application/octet-stream");
PDF 파일을 전송하는 동안 컨텐츠 유형 application / x-pdf-document 또는 application / pdf가 전송됩니다. Adobe Reader는 일반적으로이 MIME 유형에 대한 핸들러를 설정하므로 PDF MIME 유형이 수신되면 브라우저가 문서를 Adobe Reader로 전달합니다.
나는 이것에 대답하기에 너무 늦었지만 자바 스크립트에서 이것을하기위한 핵을 찾았습니다.
function downloadFile(src){
var link=document.createElement('a');
document.body.appendChild(link);
link.href= src;
link.download = '';
link.click();
}
이 시도:
<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);
다른 접근법이 있습니다. 웹 서버 로직을 사용하기 위해 브라우저 지원에 의존하거나 애플리케이션 계층에서이를 해결하는 것보다 선호합니다.
If you are using Apache, and can put an .htaccess file in the relevant directory you could use the code below. Of course, you could put this in httpd.conf as well, if you have access to that.
<FilesMatch "\.(?i:pdf)$">
Header set Content-Disposition attachment
</FilesMatch>
The FilesMatch directive is just a regex so it could be set as granularly as you want, or you could add in other extensions.
The Header line does the same thing as the first line in the PHP scripts above. If you need to set the Content-Type lines as well, you could do so in the same manner, but I haven't found that necessary.
I solved mine using the whole url of the PDF file (Instead of just putting the file name or location to href): a href="domain . com/pdf/filename.pdf"
if you need to limit download rate, use this code !!
<?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!');
}
?>
For more information click here
<!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>
In a Ruby on Rails application (especially with something like the Prawn gem and the Prawnto Rails plugin), you can accomplish this a little more simply than a full on script (like the previous PHP example).
In your controller:
def index
respond_to do |format|
format.html # Your HTML view
format.pdf { render :layout => false }
end
end
The render :layout => false part tells the browser to open up the "Would you like to download this file?" prompt instead of attempting to render the PDF. Then you would be able to link to the file normally: http://mysite.com/myawesomepdf.pdf
참고URL : https://stackoverflow.com/questions/364946/how-to-make-pdf-file-downloadable-in-html-link
'programing tip' 카테고리의 다른 글
신속한 지연 기능 (0) | 2020.07.16 |
---|---|
CodeIgniter : 컨트롤러, 액션, URL 정보를 얻는 방법 (0) | 2020.07.16 |
Yosemite에서 Ruby / Homebrew / RVM을 작동 시키려면 어떻게해야합니까? (0) | 2020.07.16 |
DateTime에서 일 빼기 (0) | 2020.07.16 |
왜 학교에서 이런 것들을 가르치지 않습니까? (0) | 2020.07.16 |