【问题标题】:How to calculate Content-Length for a file download within Kohana PHP?如何在 Kohana PHP 中计算文件下载的内容长度?
【发布时间】:2010-04-05 17:07:35
【问题描述】:

我正在尝试从 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();
}

【问题讨论】:

  • 如果您使用的是 Kohana v3,请不要使用 header("Content-Type:..."),如果您在控制器内部,请使用 $this->request->headers['Content-Type'] = $this->getFileType();

标签: php header kohana content-length


【解决方案1】:

使用 Kohana 发送文件的方法要简单得多。如果您使用的是 Kohana 2.x,则可以这样做...

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

Documentation

如果您使用的是 Kohana 3.x,它是这样完成的...

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

Documentation

【讨论】:

    【解决方案2】:

    发现我需要调用 Kohana::close_buffers(FALSE) 来清除 Kohana 的输出缓冲区。 这是一个漫长的搜索,但现在它有效。

    【讨论】:

      【解决方案3】:

      在 3.1 及更高版本中,使用

      Request::current()->response()->send_file(FILENAME);
      

      帮我挖了些东西,希望这对某人有所帮助

      Documentation

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-08
        • 1970-01-01
        • 1970-01-01
        • 2012-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多