php - 如何在 Kohana PHP 中计算文件下载的内容长度?

标签 php header kohana content-length

我尝试将 Kohana 模型中的文件发送到浏览器,但是一旦添加 Content-Length header ,该文件就不会立即开始下载。

现在问题似乎是 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();
}

最佳答案

有一种更简单的方法可以使用 Kohana 发送文件。如果您使用Kohana 2.x,则可以像这样完成...

download::force('./application/downloads/file.txt');

Documentation

如果您使用Kohana 3.x,则操作如下...

$this->request->send_file('./application/downloads/file.txt');

Documentation

关于php - 如何在 Kohana PHP 中计算文件下载的内容长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2579722/

相关文章:

php - Composer 创建本地包

php - 将变量值限制为某些预定义值

css - 在全宽固定标题内定位导航

php - Kohana orm 命令升序/降序?

php - "Could not execute Model_Hotel::__construct()"与 mysql_fetch_object,属性保持未初始化

php - 将表单值保存到 wordpress 数据库中

php - 什么是 https 和 SSL?它们是如何工作的?如何在 PHP 中使用它们?

javascript - xmlhttprequest 状态始终返回 0

javascript - 使用 get 请求头向服务器发送数据

php - 如何在 Kohana 中捕获 HTTP_Exception_404 错误