Download media content directly

Enonic version: 6.8.1

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;

      <mapping controller="/site/controller/media/media.js" order="1">
        <pattern invert="true">\/_\/attachment</pattern>

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.!/module-lib_xp_content.html#.getAttachmentStream


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