首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >强制下载附件而不是自动打开附件

强制下载附件而不是自动打开附件
EN

Stack Overflow用户
提问于 2012-09-13 10:35:55
回答 4查看 9K关注 0票数 2

我有一个网站,列出附件。点击这些附件会导致以下两种行为之一-

  1. 附件在同一窗口中打开。
  2. 附件向用户提供一个打开或保存文档的对话框。

数字1似乎只发生在PDF中,但是有什么方法可以让用户看到保存/打开/取消弹出的所有附件吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-09-13 10:46:44

只适用于PDF。

代码语言:javascript
复制
// The user will receive a PDF to download
header('Content-type: application/pdf');

// File will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The actual PDF file on the server is source.pdf
readfile('source.pdf');

..。

对于所有其他文件类型,也许您可以使用..。echo mime_content_type('Yourfile.ext') o

代码语言:javascript
复制
header('Content-type: '.mime_content_type('Yourfile.ext'));
header('Content-Disposition: attachment; filename="'.$output_filename.'"');
readfile($source_filename);

小心我还没测试过..。

内容类型标头指定要下载的文件类型,由mime类型指定。内容配置头指定要下载的文件的新文件名。readfile行不是要发送的头,而是一个PHP调用,它从一个文件中获取所有数据并输出它。传递给readfile函数的参数是要下载的实际pdf文件的位置。

更新

mime_content_type()函数是不推荐的。你要用这个代替..。

代码语言:javascript
复制
$finfo = new finfo;

$fileinfo = $finfo->file($file, FILEINFO_MIME);
票数 4
EN

Stack Overflow用户

发布于 2012-09-13 10:37:10

您需要发送适当的内容类型标头()。

例如(对于pdf,但是如果您调整mimetype,它适用于任何事情):

代码语言:javascript
复制
<?php
header('Content-disposition: attachment; filename=huge_document.pdf');
header('Content-type: application/pdf');   // make sure this is the correct mime-type for the file
readfile('huge_document.pdf');
?> 

补充案文:

download.htm

票数 1
EN

Stack Overflow用户

发布于 2012-09-13 11:47:06

以下是我在Wordpress中点击附件链接时强制下载文档所使用的完整代码,并使用@幸福an善意地提供了答案。

代码语言:javascript
复制
/**
 * Check that a page is the permalink of an attachment and force the download of the attahment if it is
 */
add_action('template_redirect', 'template_redirect');
function template_redirect(){

    global $post;

    /** Get the attachment URL as a pertty link ($url) and as a link to the file ($guid) */
    $url = get_permalink($post->ID);
    $guid = wp_get_attachment_url($post->ID);

    /** Get the file name of the attachment to output in the header */
    $file_name = basename(get_attached_file($post->ID));

    /** Get the location of the file on the server */
    $file_location = $_SERVER['DOCUMENT_ROOT'].substr($guid, strpos($guid, '/wp-content'));

    /** Get the file Mime Type */
    $finfo = new finfo;
    $mime_type = $finfo->file($file_location, FILEINFO_MIME);

    /** Check that the page we are on is a local attachment and force download if it is */
    if(is_local_attachment($url)) :

        header("Content-type: ".$mime_type, true, 200);
        header("Content-Disposition: attachment; filename=".$file_name);
        header("Pragma: no-cache");
        header("Expires: 0");

        readfile($guid); 

        exit();

    endif;

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12404344

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档