【问题标题】:PHP forced download going to webpagePHP强制下载到网页
【发布时间】:2013-07-08 11:36:22
【问题描述】:

我遇到了强制下载文件的问题。

我正在使用 PHPExcel 根据从我们的数据库中提取的信息创建一个 xls 文件。这一切都可以正常工作,并且 Excel 文件可以按要求工作。

然后我尝试使用以下函数强制下载创建的文件。但是它会下载网页而不是文件。

目前在 Win XP SP3、Notepad++、XAMPP(Apache 2.4.3、PHP 5.4.7)上开发。

**函数跟随

public function downloadfile($file){
    if(file_exists($file) && is_file($file)){           
        //ob_start();
        echo $file;
        echo "in file exists";
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);    
        //ob_end_flush();
    }else
        echo "file or location does not exist <br>";    
        echo $file;
}

任何帮助将不胜感激。 提前致谢

【问题讨论】:

    标签: php excel download webpage xls


    【解决方案1】:

    如果它是一个 excel 文件,那么只需重定向到该 url,默认情况下它会要求下载文件。

    header("Location: http://site.com/path/to/file/filename.xlsx");
    /* Make sure that code below does not get executed when we redirect. */
    exit;
    

    如果在javascript中给出

    location.href = 'http://site.com/path/to/file/filename.xlsx';
    

    【讨论】:

      【解决方案2】:
      header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
      header("Content-Disposition: inline; filename=\"" . $fileName . ".xls\"");
      header("Pragma: no-cache");
      header("Expires: 0");
      readfile($filePath);
      

      试试这个

      【讨论】:

        猜你喜欢
        • 2011-03-25
        • 1970-01-01
        • 2013-12-06
        • 2011-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多