0

I have followed Cakes Cookbook to send files (http://book.cakephp.org/3.0/en/controllers/request-response.html#sending-files) but I've been facing a weird problem. PDF's, DOC's and other binaries work just fine. But when I try to download/show an image (JPG or PNG) the file corrupts itself.

The downloaded file is not recognized as an image. It has the exactly same size of the original one, but when I diff it they are completly different.

I couldn't find anything like at the internet related to cake so I hope you can help me!

The below code is my download action

 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;
}

Response headers:

Accept-Ranges:bytes

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

Connection:Keep-Alive

Content-Length:121000

Content-Type:image/jpeg

Date:Thu, 24 Nov 2016 16:17:49 GMT

Expires:Thu, 19 Nov 1981 08:52:00 GMT

Keep-Alive:timeout=5, max=100

Pragma:no-cache

Server:Apache/2.4.10 (Ubuntu)

Community
  • 1
  • 1
Fernando Rybka
  • 238
  • 1
  • 4
  • 14

3 Answers3

0

Check your file path and MIME Types is correct.

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;
}

Example:

Your $file['filename'] variable should be /path/to/your/file.jpg

Also check the correct MIME TYPES from CakePHP 3 Sending or Downloading Files

Sumon Sarker
  • 2,707
  • 1
  • 23
  • 36
0

I've got the same problem with downloading jpg and xlsx files.

My code is quite simple:

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

Compared with 2 files (original file AND the downloaded file which is corrupted) with a binary editor, there is 1 byte difference. I don't know why but the 0x20 was added at the top of the file.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
tons
  • 1
0

I've got the same problem and I was able to solve it. The problem was caused as soon as a recent change on my source code for another controller was made so I started searching for spaces after or before the opening php tag<?php <?. Also I deleted the closures ?> for all of my php files. I know it is hard to detect where the problem comes from but make sure to check the last files you changed. i.e controllers, behaviors, models etc.

I hope it can solve your problem.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103