(HTML) 클릭시 브라우저에서 열지 않고 PDF 파일 다운로드
PDF 파일 링크를 브라우저에서 여는 대신 다운로드 가능하게 만드는 방법이 궁금합니다. 이것은 HTML에서 어떻게 이루어 집니까? (나는 그것이 자바 스크립트 또는 무언가를 통해 수행되었다고 가정합니다).
HTML로는 할 수 없습니다. 서버 기반 솔루션입니다. 브라우저가 저장 대화 상자를 트리거하도록 파일을 스트리밍해야합니다.
나는 이것을하지 않는 것이 좋습니다. 사용자가 PDF와 상호 작용하는 방법은 사용자에게 맡겨야합니다.
업데이트 (2014) :
그래서 ...이 답변은 여전히 많은 반대표를 얻습니다. 그 중 일부는 이것이 4 년 전에 답변되었다고 가정하고 Sarim이 지적했듯이 이제이를 처리 할 수 있는 HTML 5 download
속성 이 있습니다.
나는 동의하고 Sarim의 대답이 좋다고 생각합니다 (OP가 반환되면 아마도 선택한 대답이어야 함). 그러나이 답변은 여전히 신뢰할 수있는 방법입니다 (Yiğit Yener의 답변이 지적하고 이상하게도 사람들이 동의 함). 다운로드 속성이 지원을 받았지만 여전히 불안정합니다.
http://caniuse.com/#feat=download
html5로 이제 가능합니다. 요소에 "다운로드"속성을 설정합니다.
<a href="http://link/to/file" download="FileName">Download it!</a>
출처 : http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download
이것은 서버 측 코드로 http 응답 헤더를 설정하는 경우에만 가능합니다. 즉;
Content-Disposition: attachment; filename=fname.ext
전송 된 http 헤더를 변경해야합니다. 서버에 따라 다음과 같이 .htaccess를 수정할 수 있습니다.
<FilesMatch "\.(?i:pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
PHP 스크립트 (또는이를 위해 다른 서버 측 언어)를 사용해야합니다.
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
httacces를 사용하여 pdf 대신 PHP 파일로 리디렉션 (재 작성)합니다.
당신이 사용할 수있는
Response.AddHeader("Content-disposition", "attachment; filename=" + Name);
이 예를 확인하십시오.
http://www.codeproject.com/KB/aspnet/textfile.aspx
이것은 ASP.NET에 적용됩니다. 다른 모든 서버 측 언어에서 유사한 솔루션을 찾을 수 있다고 확신합니다. 그러나 내가 아는 한 자바 스크립트 솔루션이 없습니다.
html5 속성이 없으면 php를 사용하여이를 달성 할 수 있습니다.
이 코드로 download.php 라는 php 파일을 만듭니다 .
<?php
ob_start();
$file = "yourPDF.pdf"
if (file_exists($file))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit();
}
이제 자동으로 pdf 다운로드를 시작하려면이 자바 스크립트를 작성하십시오.
<script>window.location = "download.php";</script>
이것이 링크에서 작동하도록하려면 이것을 사용하십시오 ...
<a href='javascript:window.location = "download.php"'>
Download it!
</a>
새 탭에서 열 때 대신 브라우저에서 이미지 또는 pdf 파일을 직접 다운로드하려면 javascript에서 동적 링크 생성의 다운로드 속성 값을 설정해야합니다.
var path= "your file path will be here";
var save = document.createElement('a');
save.href = filePath;
save.download = "Your file name here";
save.target = '_blank';
var event = document.createEvent('Event');
event.initEvent('click', true, true);
save.dispatchEvent(event);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
For new Chrome update some time event is not working. for that following code will be use
var path= "your file path will be here";
var save = document.createElement('a');
save.href = filePath;
save.download = "Your file name here";
save.target = '_blank';
document.body.appendChild(save);
save.click();
document.body.removeChild(save);
Appending child and removing child is useful for Firefox, Internet explorer browser only. On chrome it will work without appending and removing child
The solution that worked best for me was the one written up by Nick on his blog
The basic idea of his solution is to use the Apache servers header mod and edit the .htaccess to include a FileMatch directive that the forces all *.pdf files to act as a stream instead of an attachment. While this doesn't actually involve editing HTML (as per the original question) it doesn't require any programming per se.
The first reason I preferred Nick's approach is because it allowed me to set it on a per folder basis so PDF's in one folder could still be opened in the browser while allowing others (the ones we would like users to edit and then re-upload) to be forced as downloads.
I would also like to add that there is an option with PDF's to post/submit fillable forms via an API to your servers, but that takes awhile to implement.
The second reason was because time is a consideration. Writing a PHP file handler to force the content disposition in the header() will also take less time than an API, but still longer than Nick's approach.
If you know how to turn on an Apache mod and edit the .htaccss you can get this in about 10 minutes. It requires Linux hosting (not Windows). This may not be appropriate approach for all uses as it requires high level server access to configure. As such, if you have said access it's probably because you already know how to do those two things. If not, check Nick's blog for more instructions.
As the html5 way (my previous answer) is not available in all browsers, heres another slightly hack way.
This solution requires you are serving the intended file from same domain, OR has CORS permission.
- First download the content of the file via XMLHttpRequest(Ajax).
- Then make a data URI by base64 encoding the content of the file and set media-type to
application/octet-stream
. Result should look like
data:application/octet-stream;base64,SGVsbG8sIFdvcmxkIQ%3D%3D
Now set location.href = data
. This will cause the browser to download the file. Unfortunately you can't set file name or extension this way. Fiddling with the media-type could yield something.
See details: https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs
The behaviour should depend on how the browser is set up to handle various MIME types. In this case the MIME type is application/pdf. If you want to force the browser to download the file you can try forcing a different MIME type on the PDF files. I recommend against this as it should be the users choice what will happen when they open a PDF file.
I needed to do this for files created with dynamic names in a particular folder and served by IIS.
This worked for me:
- In IIS, go that folder and double click HTTP Response Headers.
Add a new header with the following info:
Name: content-disposition Value: attachment
(from: http://forums.iis.net/t/1175103.aspx?add+CustomHeaders+only+for+certain+file+types+)
If you are using HTML5 (and i guess now a days everyone uses that), there is an attribute called download
.
ex. <a href="somepathto.pdf" download="filename">
here filename
is optional, but if provided, it will take this name for downloaded file.
Finally I found...... create dynamic anchor tag and make click on it
<script>
$('#myclick').click(function(){
$('body').append('<a id="link" href="mypdf.pdf"
download="Payment.pdf"> </a>');
$('#link')[0].click();
});
</script>
'Payment.pdf' is only for custom name .
'program tip' 카테고리의 다른 글
버튼을 클릭하고 마우스를 놓은 후에도 부트 스트랩의 툴팁이 사라지지 않습니다. (0) | 2020.08.26 |
---|---|
Join-Path를 사용하여 두 개 이상의 문자열을 파일 경로로 결합하는 방법은 무엇입니까? (0) | 2020.08.26 |
출시 후 iOS 앱에 디버거를 연결하는 방법은 무엇입니까? (0) | 2020.08.26 |
v5 UUID 생성. (0) | 2020.08.26 |
프로젝트에서 Cordova 플러그인 제거 (0) | 2020.08.26 |