Download media content directly

Enonic version: 6.8.1
OS: OSX

Hello. I want to be able to download media content directly, without using attachmentUrl. This is because there are many entries to my media content (mostly pdf files), and they are listed in the same manner as all other content – so to avoid 5 different if checks on type i thought i would handle it all the same way.

I attempted doing this via a controller using this mapping;

<mappings>
      <mapping controller="/site/controller/media/media.js" order="1">
        <match>type:'media:document'</match>
        <pattern invert="true">\/_\/attachment</pattern>
      </mapping>
</mappings>

Then i redirect it to the attachmentUrl in the controller like this;

exports.get = function (req) {
    var content = portal.getContent();
    var attachmentUrl = portal.attachmentUrl({
      id: content._id,
      download: true
    });

    return {
        redirect: attachmentUrl
    };
};

The problem is that the controller kicks in on the subroute as well, making a redirect loop. I thought maybe my attachment regex would solve this, but it didnt help.

So, is there any way to make this work or am i stuck adding a if check for type with pageUrl/attachmentUrl in 5 different parts?

You can return the contents of the attachment in the controller, instead of redirecting.
You can get the stream with getAttachmentStream() and set it in the body of the response, and use the mimeType from the attachments property in the content object.

http://repo.enonic.com/public/com/enonic/xp/docs/6.8.0/docs-6.8.0-libdoc.zip!/module-lib_xp_content.html#.getAttachmentStream

6 Likes

Perfect! Thanks, must have missed that one :smile: