1

我正在为我的应用程序使用 CakePHP 3.4+。

本地路径中有一个 XML 文件,点击链接时需要下载。在根据我的应用程序检查一些要求后,我想从控制器的操作中返回下载

public function downloadXml()
{
    if ($this->_checkMembership()) {
        try {
            // file path /webroot/agency/data.xml
            $xmlLink = WWW_ROOT . 'agency/data.xml';

            $this->response->withFile($xmlLink, [
                'download' => true,
                'name' => 'data.xml',
            ]);
            return $this->response;
        } catch (NotFoundException $e) {
            $this->Flash->error('Requested file not found. Try again');
            return $this->redirect(['action' => 'index']);
        }
    }
}

在模板中

<?= $this->Html->link(
      __('Download the site'),
      [
          'action' => 'downloadXml'
      ],
) ?>

但这仅在单击链接时显示空白页面

4

1 回答 1

4

响应方法是使用 PSR-7 不变性模式实现的with*,即它们返回一个新对象而不是修改当前对象。您必须返回新创建的对象:

return $this->response->withFile($xmlLink, [
    'download' => true,
    'name' => 'data.xml',
]);

如果您不返回自定义响应,即如果您想要呈现视图而不是返回响应对象,那么您必须重新分配新对象$this->response才能应用修改。

于 2017-11-15T12:59:00.453 回答