如何在 Kohana PHP 中计算文件下载的内容长度?
我正在尝试将 Kohana 模型中的文件发送到浏览器,但是一旦添加 Content-Length 标头,该文件就不会立即开始下载。
现在问题似乎是 Kohana 已经在输出缓冲区了。脚本开头的 ob_clean 对此没有帮助。另外,将 ob_get_length() 添加到 Content-Length 也没有帮助,因为它只返回 0。 getFileSize() 函数返回正确的数字:如果我在 Kohana 之外运行脚本,它就会起作用。
我读到 exit() 仍然调用所有析构函数,并且可能是 Kohana 之后输出了一些东西,但我不知道到底是什么。
希望有人可以帮助我...
这是我正在使用的代码:
public function download() {
header("Expires: ".gmdate("D, d M Y H:i:s",time()+(3600*7))." GMT\n");
header("Content-Type: ".$this->getFileType()."\n");
header("Content-Transfer-Encoding: binary\n");
header("Last-Modified: " . gmdate("D, d M Y H:i:s",$this->getCreateTime()) . " GMT\n");
header("Content-Length: ".($this->getFileSize()+ob_get_length()).";\n");
header('Content-Disposition: attachment; filename="'.basename($this->getFileName())."\"\n\n");
ob_end_flush();
readfile($this->getFilePath());
exit();
}
I'm trying to send a file from within a Kohana model to the browser, but as soon as I add a Content-Length header, the file doesn't start downloading right away.
Now the problem seems to be that Kohana is already outputting buffers. An ob_clean at the begin of the script doesn't help this though. Also adding ob_get_length() to the Content-Length isn't helping since this just returns 0.
The getFileSize() function returns the right number: if I run the script outside of Kohana, it works.
I read that exit() still calls all destructors and it might be that something is outputted by Kohana afterwards, but I can't find out what exactly.
Hope someone can help me out here...
This is the piece of code I'm using:
public function download() {
header("Expires: ".gmdate("D, d M Y H:i:s",time()+(3600*7))." GMT\n");
header("Content-Type: ".$this->getFileType()."\n");
header("Content-Transfer-Encoding: binary\n");
header("Last-Modified: " . gmdate("D, d M Y H:i:s",$this->getCreateTime()) . " GMT\n");
header("Content-Length: ".($this->getFileSize()+ob_get_length()).";\n");
header('Content-Disposition: attachment; filename="'.basename($this->getFileName())."\"\n\n");
ob_end_flush();
readfile($this->getFilePath());
exit();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一种更简单的方法可以使用 Kohana 发送文件。如果您使用 Kohana 2.x,它是这样完成的...
文档< /a>
如果您使用 Kohana 3.x,则操作如下...
文档
There is a much simpler way to send a file with Kohana. If you are using Kohana 2.x it's done like this...
Documentation
If you are using Kohana 3.x, it is done like this...
Documentation
发现我需要调用 Kohana::close_buffers(FALSE) 来清除 Kohana 的输出缓冲区。
这是一个漫长的搜索,但现在有效了。
Found out I needed to call Kohana::close_buffers(FALSE) to clear Kohana's output buffer.
It was a long search, but now it works.
在 3.1 及更高版本中,使用
Take me some diging 所以希望这可以帮助某人
文档
In 3.1 and forward, use
Took me some digging so hopefully this helps someone
Documentation