在CakePHP3中如何允许从控制器下载本地文件
我正在为我的应用程序使用CakePHP3.4+ 本地路径中有一个XML文件,需要在单击链接时下载。在根据我的应用程序检查了一些要求之后,我想返回控制器操作的下载在CakePHP3中如何允许从控制器下载本地文件,cakephp,cakephp-3.4,Cakephp,Cakephp 3.4,我正在为我的应用程序使用CakePHP3.4+ 本地路径中有一个XML文件,需要在单击链接时下载。在根据我的应用程序检查了一些要求之后,我想返回控制器操作的下载 public function downloadXml() { if ($this->_checkMembership()) { try { // file path /webroot/agency/data.xml $xmlLink = WWW_ROOT .
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'
],
) ?>
但这仅显示单击链接时的空白页带有*响应的
方法使用PSR-7不变性模式实现,即它们返回一个新对象,而不是修改当前对象。必须返回新创建的对象:
return $this->response->withFile($xmlLink, [
'download' => true,
'name' => 'data.xml',
]);
如果不返回自定义响应,即如果希望渲染视图而不是返回响应对象,则必须将新对象重新指定给$this->response
,以便应用修改
带有*
响应的方法是使用PSR-7不变性模式实现的,即它们返回一个新对象,而不是修改当前对象。必须返回新创建的对象:
return $this->response->withFile($xmlLink, [
'download' => true,
'name' => 'data.xml',
]);
如果不返回自定义响应,即如果希望渲染视图而不是返回响应对象,则必须将新对象重新指定给$this->response
,以便应用修改