2

When I am saving a file in a img/upload folder the file is saved with the correct file-extension.

However, when I try to download the file, a .htm file-extension is appended.

How can I avoid this? I've added my code below;

view.ctp

<?php echo $this->Form->label("Resume:");?> 
      <?php echo $this->Form->input("resume",array("class"=>"input_boxstyle_select","label"=>"","type"=>"file","id"=>"file"));?> 
      <a href="../download_resume/<?php echo $editEmpPros[0]['prospective_employee']['resume']?>" style="margin-left:140px;color:#0477CA;"> <?php echo $editEmpPros[0]['prospective_employee']['resume']?> </a> 

Inside my controller:

public function download_resume($id=null)
{
    $LUser = $this->Session->read('username');  
    $this->disableCache(); 
    if (!$LUser) {
        $this->redirect(array("action"=>"../"));                 
    }

    $path="../webroot/img/upload/$id";
    header('Content-Disposition: attachment'); readfile($path);
    //print_r(readfile($path));
    exit;
}
4

4 回答 4

3

在 CakePHP 2.x 中处理文件下载

虽然其他解决方案可能有效,但 CakePHP 通过CakeResponseobject处理响应。手册中的这一章描述了如何发送(下载)文件;发送文件

响应将根据文件扩展名自动尝试设置正确的 mime 类型

输出文件(在浏览器内);

$this->response->file(WEBROOT_DIR . '/img/upload/' . $filename);

//Return reponse object to prevent controller from trying to render a view
return $this->response;

下载文件(并且可以选择指定自定义文件名)

要强制下载文件并指定自定义文件名(如果需要),请使用此代码。CakeResponse 对象将自动设置正确的标题,因此不需要手动指定自定义文件

// To force *downloading* the file and specify a custom filename (if desired)
$this->response->file(
    WEBROOT_DIR . '/img/upload/' . $filename,
    array(
        'download' => true,
        'name'     => 'custom-filename-for-downloading'
    )
);
return $this->response;
于 2013-05-03T10:28:43.600 回答
2

您也可以在 Content-Disposition 标头中提供文件名,如下所示:

Content-Disposition: attachment; filename="foo.bar"
于 2013-05-03T08:37:58.987 回答
1

根据您必须支持的浏览器,您还可以使用downloadHTML5 的属性:

<a href="/path-to-your-file" download="your-desired-filename">my link</a>
于 2013-05-03T15:08:30.583 回答
0

你必须设置一些参数,因为这里我给你一个例子来下载 PDF 文件

<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>

请根据需要制作参数..

让我知道我是否可以为您提供更多帮助。

于 2013-05-03T09:55:29.800 回答