Programing

다운로드하지 않고 브라우저에서 파일을 강제로 열려면 어떻게합니까 (PDF)?

crosscheck 2020. 5. 15. 20:56
반응형

다운로드하지 않고 브라우저에서 파일을 강제로 열려면 어떻게합니까 (PDF)?


"브라우저에서 PDF 표시"옵션을 선택하지 않은 경우 브라우저에서 PDF 파일을 강제로 열 수있는 방법이 있습니까?

embed 태그와 iframe을 사용해 보았지만 해당 옵션을 선택한 경우에만 작동합니다.

어떡해?


브라우저에 파일을 보도록 브라우저에 알리려면 HTTP 응답에 다음 헤더가 포함되어야합니다.

Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"

보지 않고 파일을 다운로드 하려면 :

Content-Type: application/pdf
Content-Disposition: attachment; filename="filename.pdf"

파일 이름에 특수 문자가 포함 된 경우 파일 이름을 따옴표로 묶어야합니다 filename[1].pdf.

HTTP 응답 헤더를 설정하는 방법은 HTTP 서버에 따라 다릅니다 (또는 서버 측 코드에서 서버 응답 : 서버 측 프로그래밍 언어).


HTML5를 사용하고 있다면 (현재 모든 사람들이 사용한다고 생각합니다)라는 속성이 download있습니다.

예를 들어

<a href="somepathto.pdf" download="filename">

다음은 filename선택 사항이지만, 제공하는 경우, 다운로드 한 파일이 이름을 소요됩니다.


올바른 유형은 application/pdfPDF가 아닌 PDF에 대한 것 application/force-download입니다. 이것은 일부 레거시 브라우저의 해킹처럼 보입니다. 가능하면 항상 올바른 MIME 유형을 사용하십시오.

서버 코드를 제어 할 수있는 경우 :

  • 강제 다운로드 / 프롬프트 : 사용 header("Content-Disposition", "attachment; filename=myfilename.myextension");
  • 브라우저가 열려고 시도합니다 : 사용 header("Content-Disposition", "inline; filename=myfilename.myextension");

서버 코드를 제어 할 수 없습니다 :

참고 : 자세한 정보가 있고 공통 코드를 사용할 수 있으므로 서버 측에서 파일 이름을 설정하는 것이 좋습니다.


아파치가 있다면 이것을 .htaccess파일에 추가 하십시오 :

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

이전 게시물에 입력 오류가있었습니다.

    header("Content-Type: application/force-download");
    header("Content-type: application/pdf");
    header("Content-Disposition: inline; filename=\"".$name."\";");

브라우저에서 사용자에게 프롬프트를 표시하지 않으려면 "첨부 파일"대신 세 번째 문자열에 "인라인"을 사용하십시오. 인라인은 매우 잘 작동합니다. 사용자에게 열기를 클릭하도록 요청하지 않고 PDF가 즉시 표시됩니다. "첨부 파일"을 사용했는데 사용자에게 열기, 저장을 요청하는 메시지가 표시됩니다. 브라우저 설정 너트를 변경하려고했지만 프롬프트가 표시되지 않습니다.


이것은 ASP.NET MVC 용입니다.

cshtml 페이지에서 :

<section>
    <h4><a href="@Url.Action("Download", "Document", new { id = @Model.GUID })"><i class="fa fa-download"></i> @Model.Name</a></h4>
    <object data="@Url.Action("View", "Document", new { id = @Model.GUID })" type="application/pdf" width="100%" height="800" class="col-md-12">
        <h2>Your browser does not support viewing PDFs, click on the link above to download the document.</h2>
    </object>
</section>

컨트롤러에서 :

public ActionResult Download(Guid id)
    {
        if (id == Guid.Empty)
            return null;

        var model = GetModel(id);

        return File(model.FilePath, "application/pdf", model.FileName);
    }

public FileStreamResult View(Guid id)
    {
        if (id == Guid.Empty)
            return null;

        var model = GetModel(id);

        FileStream fs = new FileStream(model.FilePath, FileMode.Open, FileAccess.Read);

        return File(fs, "application/pdf");
    }

CodeIgniter를 사용중인 경우

설정하십시오 :

$htmlpdf -> Output($pdf_local_path, f); to $htmlpdf -> Output(); exit;

루트 파일에서 downloads.php를 엽니 다.

그런 다음 186 행으로 이동하여 다음으로 변경하십시오.

        if(preg_match("/\.jpg|\.gif|\.png|\.jpeg/i", $name)){
            $mime = getimagesize($download_location);
            if(!empty($mime)) {
                header("Content-Type: {$mime['mime']}");
            }
        }
        elseif(preg_match("/\.pdf/i", $name)){
            header("Content-Type: application/force-download");
            header("Content-type: application/pdf");
            header("Content-Disposition: inline; filename=\"".$name."\";");
        }

        else{
            header("Content-Type: application/force-download");
            header("Content-type: application/octet-stream");
            header("Content-Disposition: attachment; filename=\"".$name."\";");
        }

다음과 같은 방법으로이를 수행 할 수 있습니다.

<a href="path to PDF file">Open PDF</a>

If the PDF file is inside some folder and that folder doesn't have permission to access files in that folder directly then you have to bypass some file access restrictions using .htaccess file setting by this way:

<FilesMatch ".*\.(jpe?g|JPE?G|gif|GIF|png|PNG|swf|SWF|pdf|PDF)$" >
    Order Allow,Deny
    Allow from all
</FilesMatch>

But now allow just certain necessary files.

I have used this code and it worked perfectly.


Either use

<embed src="file.pdf" />

if embedding is an option or my new plugin, PIFF: https://github.com/terrasoftlabs/piff


Here is another method of forcing a file to view in the browser in PHP:

$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$url = 'uploads/'.$file_name;
        echo '<html>'
                .header('Content-Type: application/'.$extension).'<br>'
                .header('Content-Disposition: inline; filename="'.$file_name.'"').'<br>'
                .'<body>'
                .'<object   style="overflow: hidden; height: 100%;
             width: 100%; position: absolute;" height="100%" width="100%" data="'.$url.'" type="application/'.$extension.'">
                    <embed src="'.$url.'" type="application/'.$extension.'" />
             </object>'
            .'</body>'
            . '</html>';

Just open Adobe Reader, menu → EditPreferencesInternet, then change to browser mode or for detailed instructions on different browsers try Display PDF in browser | Acrobat, Acrobat Reader.


If you link to a .PDF it will open in the browser.
If the box is unchecked it should link to a .zip to force the download.

If a .zip is not an option, then use headers in PHP to force the download

header('Content-Type: application/force-download'); 
header('Content-Description: File Transfer'); 

참고URL : https://stackoverflow.com/questions/6293893/how-do-i-force-files-to-open-in-the-browser-instead-of-downloading-pdf

반응형