【问题标题】:How to serve a remote file as a download with CakePHP 3?如何使用 CakePHP 3 提供远程文件作为下载?
【发布时间】:2017-09-29 16:45:34
【问题描述】:

我想从远程 NAS 服务器下载文件,我无法强制下载到客户端。我正在使用这个功能:

    public function download(){
    // Set IP and port
    define("FTP_CONNECT_IP", "xxx");
    define("CONNECT_PORT", "21");

    // Set username and password
    define("FTP_LOGIN_USER", "username");
    define("FTP_LOGIN_PASS", "password");
    $remote_file = 'ftp://' . FTP_LOGIN_USER . ':' . FTP_LOGIN_PASS . '@' . FTP_CONNECT_IP . '/' .'PathToFile.avi';
    $response = $this->response->withFile($remote_file,['download' => true]);
    return  $response;

    }

它开始读取某些内容,但浏览器从不要求我下载。请问怎么了?

【问题讨论】:

    标签: php cakephp download ftp cakephp-3.x


    【解决方案1】:

    您不能将Response::withFile() 用于远程文件,它仅适用于本地文件。

    如果你想提供远程文件,那么你要么必须将它们临时存储在你的服务器上,要么自己构建一个适当的下载响应,例如使用 CakePHPs 回调流来手动输出数据。

    这是一个简单的示例(不支持范围请求):

    return $this->response
        ->withType(pathinfo($remote_file, \PATHINFO_EXTENSION))
        ->withDownload(basename($remote_file))
        ->withLength(filesize($remote_file))
        ->withBody(new \Cake\Http\CallbackStream(function () use ($remote_file) {
            ob_end_flush();
            ob_implicit_flush();
            readfile($remote_file);
        }));
    

    另见

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      相关资源
      最近更新 更多