header实现文件下载的问题

WBOY
发布: 2023-03-01 20:38:02
原创
1275 人浏览过

需要实现点击button然后获取信息,将内容以文件形式下载下来。
但是现在点击button是打开新窗口并且展示出内容,而不是弹出下载窗。
代码如下:

<code>$filename = $this->input->cookie('merchant_id');
$timestamp = date("YmdHis",time());
$filename .= $timestamp.'.'.$fileType;

$title = mb_convert_encoding($title,'gbk','utf-8');

header('Content-type: application/octet-stream');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Content-Disposition: attachment; filename=' . $filename);
echo $title;

$ret = $this->download_model->QueryList($Req, $Resp);
$content = $this->GetDownLoadContentNew($ret['bill_list'], $fileType);
echo $content;
</code>
登录后复制
登录后复制

其中GetDownLoadContentNew是对内容进行相应的格式化。
不知道哪里有问题或者有什么地方没注意到?希望大家帮忙看下,谢谢。(fileType是csv或txt,在不同浏览器上都是一样都无法触发下载)

回复内容:

需要实现点击button然后获取信息,将内容以文件形式下载下来。
但是现在点击button是打开新窗口并且展示出内容,而不是弹出下载窗。
代码如下:

<code>$filename = $this->input->cookie('merchant_id');
$timestamp = date("YmdHis",time());
$filename .= $timestamp.'.'.$fileType;

$title = mb_convert_encoding($title,'gbk','utf-8');

header('Content-type: application/octet-stream');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Content-Disposition: attachment; filename=' . $filename);
echo $title;

$ret = $this->download_model->QueryList($Req, $Resp);
$content = $this->GetDownLoadContentNew($ret['bill_list'], $fileType);
echo $content;
</code>
登录后复制
登录后复制

其中GetDownLoadContentNew是对内容进行相应的格式化。
不知道哪里有问题或者有什么地方没注意到?希望大家帮忙看下,谢谢。(fileType是csv或txt,在不同浏览器上都是一样都无法触发下载)

<code>/**
  * 强制下载文件 
  * @param string $file 文件路径 
*/
function force_download($file){ 
    if ((isset($file)) && (file_exists($file))) {
        header("Content-length: ".filesize($file)); 
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment;filename="'.basename($file).'"'); 
        readfile($file); } 
    else { 
        echo "No file selected"; 
    }
}
//使用示例
force_download('./test.jpg');</code>
登录后复制
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!