强制下载文件破碎标题错误?

时间:2011-12-08 15:46:33

标签: php header save download

if($_POST['mode']=="save") {
$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/mcboeking/";
$path = $root.$path;
$file_path = $_POST['path'];
$file = $path.$file_path;

if(!file_exists($file)) {
    die('file not found');
} else {
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header('Content-Type: application/force-download');
    header("Content-Disposition: attachment; filename=\"".basename($file)."\";" );
    header("Content-Length: ".filesize($file));
    readfile($file);}}

我下载文件并打开它后会收到错误消息。当我尝试打开.doc文件时,我收到消息:文件结构无效。 当我尝试打开.jpg文件时:无法打开此文件。它可能已损坏或预览无法识别的文件格式。

但是当我下载PDF文件时,它们会毫无问题地打开。

有人可以帮助我吗?

P.S。我试过不同的标题包括: header('Content-Type:application / octet-stream');

4 个答案:

答案 0 :(得分:0)

您的标题与实际内容无关,因此问题是实际内容存在问题。

此外,您真的不应该尝试通过更改Content-Type标头来强制下载。保持它应该是什么。让客户决定如何处理它。

答案 1 :(得分:0)

确保除了readfile()数据之外不输出任何内容:确保PHP代码在PHP文件的第一个符号处以<?开头,并且在关闭后没有符号?>位于文件末尾,如空格或换行符(或完全删除?>)。

答案 2 :(得分:0)

$fsize = filesize($yourFilePath); 
$allowed_ext = array (

  // archives
  'zip' => 'application/zip',

  // documents
  'pdf' => 'application/pdf',
  'doc' => 'application/msword',
  'xls' => 'application/vnd.ms-excel',
  'ppt' => 'application/vnd.ms-powerpoint',

);
$mtype = mime_content_type($file_path);
if ($mtype == '') {
    $mtype = "application/force-download";
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: $mtype");
header("Content-Disposition: attachment; filename=\"$asfname\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fsize);
//then ur rest code

答案 3 :(得分:0)

在NOTEPAD中打开PHP文件。按“另存为”,然后选择“ASCI”文件格式。这有助于我的情况,因为文件是UTF8格式,这就是原因。

相关问题