Zend Framework中header下载文件的问题及解决

问题描述:

在使用Zend Framework框架开发过程中需要用户下载excel文件的功能。之前看过PHP的header()函数可以下载文件,于是便查了一下header函数,W3School中给出的用法是:

header(string,replace,http_response_code)
参数 描述
string 必需。规定要发送的报头字符串。
replace

可选。指示该报头是否替换之前的报头,或添加第二个报头。

默认是 true(替换)。false(允许相同类型的多个报头)。

http_response_code 可选。把 HTTP 响应代码强制为指定的值。(PHP 4 以及更高版本可用)

以下为下载pdf的例子:

<?php
header("Content-type:application/pdf");//不同类型的文件代码不同
// 文件将被称为 downloaded.pdf
header("Content-Disposition:attachment;filename=".$name);//这是下载时显示的名字,不含路径
// PDF 源在 original.pdf 中
readfile($fileName);//$fileName可以是路径
?>

在网上找了个下载Execel的代码:

出处:http://www.oschina.net/code/snippet_98890_27376

01 if (file_exists(CACHE_PATH . $file_name)){
02             //$this->logger->error('file realpath:'.realpath(CACHE_PATH . $file_name));
03             header( 'Pragma: public' );
04             header( 'Expires: 0' );
05             header( 'Content-Encoding: none' );
06             header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
07             header( 'Cache-Control: public' );
08             header( 'Content-Type: application/vnd.ms-excel'); 
09             header( 'Content-Description: File Transfer' );
10             header( 'Content-Disposition: attachment; filename=' $file_name );
11             header( 'Content-Transfer-Encoding: binary' );
12             header( 'Content-Length: ' filesize ( CACHE_PATH . $file_name ) );
13             readfile ( CACHE_PATH . $file_name );
14         else {
15             $this->logger->error('export model :'.$id.' 错误:未生产文件');
16             echo '<script>alert(\'export error, file not exists!\')</script>';
17         }

我将代码应用到Zend Framework中的一个action中,此action是有对应前端phtml页面的,当用户发出下载文件的请求时,文件可以下载,显示文件大小都正常,可是打开excel文件报错,提示文件类型与扩展名不一致。



从显示的问题可以推断,文件并非我们想要的excel格式文件,似乎是一个网页,找不到css文件。是下载文件的代码有问题么?


解决方法:

我将下载文件的代码单独拿出来试验,放在Apache服务器的根目录下,在浏览器中打开试验文件,发现下载正常,文件也可以打开。

倒腾了一些时间发现仅仅是因为一个函数在作怪,exit(); !!!!!

在下载文件的代码中readfile ()后就截止了,而我在框架中的action方法里readfile()函数后面没有加入exit()函数,使得错误的发生。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值