CakePHP 3图像下载损坏

时间:2016-11-24 04:48:25

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

我已经跟随Cakes Cookbook发送文件(http://book.cakephp.org/3.0/en/controllers/request-response.html#sending-files),但我一直面临着一个奇怪的问题。 PDF,DOC和其他二进制文件工作得很好。但是当我尝试下载/显示图像(JPG或PNG)时,文件会自行破坏。

下载的文件无法识别为图像。它具有与原始尺寸完全相同的尺寸,但是当我区分时它们完全不同。

我在网上找不到与蛋糕相关的东西,所以我希望你能帮助我!

以下代码是我的下载操作

 public function arquivo($id) {
    $file = $this->Arquivos->get( $id );

    $this->response->file($file['filename'], ['download' => true]);
    // Return response object to prevent controller from trying to render
    // a view.

    return $this->response;
}

回复标题:

  

接受-范围:字节

     

Cache-Control:no-store,no-cache,must-revalidate,post-check = 0,pre-check = 0

     

连接:保持活动

     

的Content-Length:121000

     

内容类型:image / JPEG

     

日期:2016年11月24日星期四16:17:49 GMT

     

Expires:Thu,1981年11月19日08:52:00 GMT

     

保持活跃:超时= 5,最大= 100

     

杂注:无缓存

     

服务器:Apache / 2.4.10(Ubuntu)

3 个答案:

答案 0 :(得分:0)

检查您的文件路径和MIME类型是否正确。

public function arquivo($id) {
    $file = $this->Arquivos->get( $id );
    $this->response->file(
        $file['filename'], #Check $file['filename'] is full path of your download file
        [
           'download' => true,
           'name' => 'Your_Download_File_Name_Here'
        ]
    );
    return $this->response;
}

示例:

您的$file['filename']变量应为/path/to/your/file.jpg

  

同时检查CakePHP 3 Sending or Downloading Files

中的正确MIME TYPES

答案 1 :(得分:0)

我在下载jpg和xlsx文件方面遇到了同样的问题。

我的代码非常简单:

public function download() {
    $response = $this->response->withFile($template_file_path, ['download' => true]);
    return $response;
}

与使用二进制编辑器的2个文件(原始文件和已损坏的下载文件)相比,存在1个字节的差异。我不知道为什么,但0x20被添加到文件的顶部。

答案 2 :(得分:0)

我遇到了同样的问题,并且能够解决。该问题是由于对另一个控制器的源代码进行了最新更改而导致的,因此我开始在打开php标签<?php <?之前或之后搜索空格。我也删除了所有PHP文件的闭包?>。我知道很难检测出问题的根源,但是请确保检查最后更改的文件。即控制器,行为,模型等。

我希望它可以解决您的问题。