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;
    }
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd