views:

48

answers:

1

Hi there!

I'm trying to create a batch action (symfony admin) that enables the creation/download on the fly of zip file containing users photos which are avaialable on the uploads/images directory.

Here is the code that I already implemented:

public function executeBatchDownloadFotos(sfWebRequest $request)
    {
        $zip = new ZipArchive();

        // atheletes identifiers
        $ids = $request->getParameter('ids');

        // get all the atheletes objects
        $q = Doctrine_Query::create()
            ->from('Atleta a')
            ->whereIn('a.id', $ids);

        foreach ($q->execute() as $atleta)
        {
            $zip->addFile($atleta->id . '_' . $atleta->Clube . '.jpg', 'uploads/atletas/' . $atleta->id . '_' . $atleta->Clube . '.jpg');
        }
    }

By the other hand, here is the view configuration:

BatchDownloadFotos:
  http_metas:
    content-type: application/zip
  has_layout:     false

For some reason, each time execute the batch action, the browser do not prompts me with the window to download the zip file.

Can anyone give some help?

Thanks in advance, Best regards!

+1  A: 

After you create ZIP archive in your controller file you should send the content to the browser.

You can do this using methods described here: http://www.symfony-project.org/gentle-introduction/1_4/en/06-Inside-the-Controller-Layer#chapter_06_sub_action_termination

Now you are trying to create ZIP file, but you are not sending it to the browser. You should use setContent() and setHttpHeader() methods.

Your action could look like this (you should add error handling):

public function executeIndex(sfWebRequest $request)
{
  $fileName = '/tmp/test.zip';
  $zip = new ZipArchive();

  $zip->open($fileName, ZipArchive::CREATE);

  // add some files to archive
  $zip->addFile('/tmp/test', 'test.txt');

  $zip->close();

  $this->getResponse()->setContent(file_get_contents($fileName));
  $this->getResponse()->setHttpHeader('Content-Type', 'application/zip');
  $this->getResponse()->setHttpHeader('Content-Disposition',
    'attachment; filename=download.zip');

  return sfView::NONE;
}
Michał Pipa
Hi there!What should I place inside the setHttpHeader() method?Thanks for the help!Best regards!
Rui Gonçalves
You should set name and value of HTTP header: http://www.symfony-project.org/api/1_4/sfWebResponse#method_sethttpheader. So, in your case it should be "Content-Type" and "application/zip". You should also set "Content-Disposition" header: http://en.wikipedia.org/wiki/MIME#Content-Disposition
Michał Pipa
Hi there!Running your code, I have noticed that the test.zip file is not created in the /tmp/ directory.Any idea why this problem is occurring?Thanks for all the help,Best regards!
Rui Gonçalves
Check if you have loaded zip extension. You can run 'php -m' command or use phpinfo() function.
Michał Pipa