Force to open “Save As…” popup open at text link click for PDF in HTML

后端 未结 18 1173
無奈伤痛
無奈伤痛 2020-11-22 10:28

I have some big size PDF catalogs at my website, and I need to link these as download. When I googled, I found such a thing noted below. It should open the \"Save As

18条回答
  •  失恋的感觉
    2020-11-22 10:59

    Meta tags are not a reliable way to achieve this result. Generally you shouldn't even do this - it should be left up to the user/user agent to decide what do to with the content you provide. The user can always force their browser to download the file if they wish to.

    If you still want to force the browser to download the file, modify the HTTP headers directly. Here's a PHP code example:

    $path = "path/to/file.pdf";
    $filename = "file.pdf";
    header('Content-Transfer-Encoding: binary');  // For Gecko browsers mainly
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
    header('Accept-Ranges: bytes');  // Allow support for download resume
    header('Content-Length: ' . filesize($path));  // File size
    header('Content-Encoding: none');
    header('Content-Type: application/pdf');  // Change the mime type if the file is not PDF
    header('Content-Disposition: attachment; filename=' . $filename);  // Make the browser display the Save As dialog
    readfile($path);  // This is necessary in order to get it to actually download the file, otherwise it will be 0Kb
    

    Note that this is just an extension to the HTTP protocol; some browsers might ignore it anyway.

提交回复
热议问题