when opened with winrar, Zip file obtained through

2019-07-20 18:38发布

问题:

What i am trying to achieve: Force download a zip file that contains user opted pdf files.

What i did in controller to achieve this:

  1. Generate pdf reports in folder APP.WEBROOT_DIR.DS."package_files" (i used MPDF library) *it generates correct readable pdf. I call here $this->render();

  2. With Zip feature of php, Generate package.zip (which consists pdf files from above specified folder) *it generates correct zip file, when downloaded from server it opens as valid zip file in windows.

  3. Set the controller viewClass to Media and set parameters to force download as zip file, *Again here I call here $this->render(); Issue: When i run i get zip file but when opened with winrar, Zip file obtained reports Unexpected end of archive.

I am not getting any usefull articles to get through this issue...

What i guess is calling two times render is making file corrupt Thanks

My controller code:

/** before this code i generate pdf files and have no issue **/

/** now scan through the directory and add all the pdf files to a zip archive **/

    $dir = new Folder("".APP.WEBROOT_DIR.DS."package_files");


    $files = $dir->find('.*\.pdf');
    $zip = new ZipArchive();
    foreach ($files as $file) {
        $file_path = $dir->pwd() . DS . $file;


        $filename =  $dir->pwd() . DS ."package.zip";

        if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
            exit("cannot open <$filename>\n");
        }  
        $zip->addFile($file_path,$file);




    }

    $zip->close(); 

/** now render the action to download the generated zip file **/

     $this->viewClass = 'Media';


        $params = array(
            'id'        => 'package.zip',
            'name'      => 'packaged_file',
            'download'  => true,
            'extension' => 'zip',
            'path'      => APP . WEBROOT_DIR.DS.'package_files' . DS
        );
        $this->set($params);
    $this->render();

回答1:

at fisrt if you use Cakephp 2.3 use cake response file instaed of mediaView with these structure:

$this->response->file($file['path']);
// Return response object to prevent controller from trying to render
// a view
return $this->response;

here is doc: http://book.cakephp.org/2.0/en/controllers/request-response.html#cake-response-file

else remove $this->render(); at the end of your action and specify mime type option specially for zip and rar file for example for docx file add mime type option like:

// Render app/webroot/files/example.docx
    $params = array(
        'id'        => 'example.docx',
        'name'      => 'example',
        'extension' => 'docx',
        'mimeType'  => array(
            'docx' => 'application/vnd.openxmlformats-officedocument' .
                '.wordprocessingml.document'
        ),
        'path'      => 'files' . DS
    );