强制浏览器下载文件,而不是打开

问题描述:

我使用的是典型的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文件

  1. :在.htaccess文件

    <FilesMatch "\.(?i:doc)$"> 
        ForceType application/octet-stream 
        Header set Content-Disposition attachment 
    </FilesMatch> 
    
  2. AddType application/octet-stream .doc 
    
  3. 在PHP脚本

    header('Content-Type: application/force-download'); 
    
+0

您是否尝试过使用[HTML5](HTTP://更新。 html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download)? – kero 2013-04-20 19:34:28

添加到您的标题:

header("Content-type: application/force-download"); 
+0

我目前无法测试它,但确实有效吗? oO – xsign 2013-04-20 20:12:11

+2

为什么我会发布它? :) – 2013-04-20 20:15:34

+0

非常感谢分享这些信息!我会明智地使用它:-) – xsign 2013-04-20 20:20:14

下面的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类型 ...

希望这有助于:)