我有一个网站,列出附件。点击这些附件会导致以下两种行为之一-
数字1似乎只发生在PDF中,但是有什么方法可以让用户看到保存/打开/取消弹出的所有附件吗?
发布于 2012-09-13 10:46:44
只适用于PDF。
// 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
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()函数是不推荐的。你要用这个代替..。
$finfo = new finfo;
$fileinfo = $finfo->file($file, FILEINFO_MIME);发布于 2012-09-13 10:37:10
您需要发送适当的内容类型标头()。
例如(对于pdf,但是如果您调整mimetype,它适用于任何事情):
<?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
发布于 2012-09-13 11:47:06
以下是我在Wordpress中点击附件链接时强制下载文档所使用的完整代码,并使用@幸福an善意地提供了答案。
/**
* 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;
}https://stackoverflow.com/questions/12404344
复制相似问题