File()->download() breaking the file

Hey,

I have been playing around with the download() command to be able to download files which i locked from public with htaccess but it seems like when the download process is starting and seeming to finish, the downloaded file seems to be corrupted.

I simply used this line of code, is there any other required things to get a working file??

<?php $page->file('ebook.pdf')->download(); ?>

Do you have some plugins installed? Try removing them all and see if this fixes it. I saw that some plugins create some unwanted output, which is not good. You should also not use the html minification plugin in combination since it will compress all output, even the file content and this leads to corrupted download files.

No plugin or HTML minification.

Just basic htacess to deny file from public.

And the code just as I described above.

For the time beings I changed the line above with some php I found on the internet.

Could you resolve this problem already? And if, could you share how? :smiley:

i have used pretty standart php code for downloading instead…

I am facing the exact same problem at the moment.

<a href="<?php echo $page->file('banana.jpg')->download(); ?>">Download</a>

this code downloads the file on page load and corrupts the file.
Any idea how to fix it?

1 Like

Shouldn’t it be rather this?

<a href="<?php echo $page->file('banana.jpg')->url(); ?>">Download</a>

I’d like to have the file automatically download. (it will be a .mp3 instead of a jpg later).
So the ->url() does not really help.

You should check out the download docs:
http://getkirby.com/docs/cheatsheet/file/download

It’s not meant to be included as an a-tag href.

c::set('routes', array(
  array(
    'pattern' => 'download/latest',
    'action'  => function() {

      page('download')
        ->files()
        ->get('32.mp3')
        ->download();

    }
  )
));

using this now in my config.php.
next problem: any idea how to route the same url to different files for different users?

c::set('routes', array(
  array(
    'pattern' => 'download/latest',
    'action'  => function() {

      if($user = site()->user('pirate32')->isCurrent()) {
          page('download')
        ->files()
        ->get('32.mp3')
        ->download();
        } elseif($user = site()->user('pirate64')->isCurrent()) {
          page('download')
        ->files()
        ->get('banana.jpg')
        ->download();
        } else {
          header::forbidden();
          die('Unauthorized access');
        }

    }
  ),
  array(
    'pattern' => 'logout',
    'action'  => function() {
      if($user = site()->user()) $user->logout();
      go('/');
    }
  )
));

found a solution now

just my 2c on this old thread. adding attr download to the a-element will also work nicely with modern browsers.