dsfb20227 2013-08-08 16:59 采纳率: 0%
浏览 24

添加标题不会使文件下载

It's pretty well documented that adding a header is the way to make a link downloadable, but I must be doing something wrong. I write the file, and then produce some HTML linking to it, but the file will not download, only appear in the browser.

<?

   //unique id
   $unique = time();

   $test_name = "HTML_for_test_" . $unique . ".txt";

   //I should put the file name I want the header attached to here (?)
   header("Content-disposition: attachment;filename=$test_name");

   $test_handler = fopen($test_name, 'w') or die("no");

   fwrite($test_handler, $test);
   fclose($test_handler);

?>

<a href="<?=$test_name">Download File</a>
  • 写回答

2条回答 默认 最新

  • dongxifu5009 2013-08-08 17:01
    关注

    Well you are just echoing an HTML tag - you should read the file content instead, like proposed on PHP Doc:

    <?php
    $file = 'monkey.gif';
    
    if (file_exists($file)) {
        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);
        exit;
    }
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源