强制浏览器下载文件,而不是打开
问题描述:
我使用的是典型的PHP代码下载文件:强制浏览器下载文件,而不是打开
header('Content-Type: ' . $mimeTypes[$fileext]);
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Cache-Control: private');
header('Pragma: private');
readfile($filepath);
一切正常 - 下载/另存为对话框打开,除非它试图.doc文件在docs.google.com中打开,但由于缺少权限而失败 - 这是因为我正在从网站根外部提供文件。
那么,如何绕过docs.google并强制每浏览器提供保存为对话框,而不管文件MIME类型? ('doc' => 'application/msword')
我尝试以下无济于事:在.htaccess文件
-
:在.htaccess文件
<FilesMatch "\.(?i:doc)$"> ForceType application/octet-stream Header set Content-Disposition attachment </FilesMatch>
-
:
AddType application/octet-stream .doc
- 在PHP脚本
:
header('Content-Type: application/force-download');
答
下面的PHP为我工作
header("Cache-Control: private");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$file."");
header("Content-Transfer-Encoding: binary");
header("Content-Type: binary/octet-stream");
readfile ($link);
附: - 我以前只在$file
变量的文件扩展名,所以没有必要提及MIME类型 ...
希望这有助于:)
您是否尝试过使用[HTML5](HTTP://更新。 html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download)? – kero 2013-04-20 19:34:28