2

I have a template called download that receives an asset ID, looks it up and should force the browser to download the file. I've gotten this far with the {% headers %} tag, but I can't figure out how to read the raw contents of the file and output it.

{% set asset = craft.assets.id(craft.request.getLastSegment()).first() %}
{% header 'Content-Description: File Transfer' %}
{% header 'Content-Type: '~asset.mimetype %}
{% header 'Content-Disposition: attachment; filename='~asset.filename %}
{% header 'Content-Transfer-Encoding: binary' %}
{% header 'Expires: 0' %}
{% header 'Cache-Control: must-revalidate' %}
{% header 'Pragma: public' %}
{% header 'Content-Length: '~asset.size %}
{# How to print raw contents of asset.url ??? #}

Can anyone help?

3

I don't think you're going to be able to do this out-of-the-box, but should be stupidly simple with a quick plugin that registers its own Twig extension. See here for an example.

That extension would add a Twig function that's basically just a simple wrapper for PHP's file_get_contents.

Then from your template, you'd do something like:

{# Get the file contents #}
{% set contents = file('/path/to/asset.zip') %}

{# output it #}
{{ contents }}
  • 1
    For anyone looking, I'm using this plugin. I made my own fork so that environment variables are parsed properly. github.com/someoneandsons/craft-yii-sendfile – Mike Pierce Jan 8 '15 at 10:24
  • Ahh yeah... forgot we had a sendFile() method! – Brad Bell Jan 8 '15 at 16:45
  • One thing the plugin wouldn't handle would be assets from external sources (S3 etc), but I think that's a job for another day. For my use case, this did the job. – Mike Pierce Jan 8 '15 at 20:49
  • @MikePierce I tried your plugin with asset from external links and it actually worked. Thanks! – Anya Dit Aug 9 '17 at 10:32
  • @MikePierce I've been using your little plugin on one of my sites and it's been working great. However I've just switched the site to https:// and now the plugin fails. Any ideas? – Lettie Nov 25 '17 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.