How to get Sitecore media elements to load (images)?

I need to have a force download action after clicking the link to the Sitecore media channel. I did not find useful Sitecore how to do this.

In the Sitecore configuration, you can determine which mime types will be loaded by force. But the problem is if you want to do this for images. Because if you do it

<mediaType name="JPEG image" extensions="jpg, jpeg, jpe">
    <mimeType>image/jpeg</mimeType>
    <forceDownload>true</forceDownload>
</mediaType>

all images will disappear due to the fact that the browser will not be able to present them in HTML!

How do I get all Sitecore media files to load by click?

+4
source share
1 answer

Sitecore , - Sitecore MediaRequestHandler.

, ? URL-, - "dl = 1"

public class MediaRequestHandler : Sitecore.Resources.Media.MediaRequestHandler, System.Web.SessionState.IRequiresSessionState
{
    protected override bool DoProcessRequest(HttpContext context, MediaRequest request, Media media)
    {
        // identify query string param from requested URL
        bool isDownload = Utils.UrlUtils.HasQueryParam(context.Request.Url, "dl", "1");
        if (isDownload)
        {
            using (MediaStream stream = media.GetStream())
            {
                // we have to check if file is not already force downloaded by Sitecore
                if (!stream.ForceDownload)
                {
                    string mediaName = media.MediaData.MediaItem.Name + "." + media.MediaData.Extension;
                    context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + mediaName + "\"");
                }
                context.Response.AddHeader("Content-Length", stream.Length.ToString());
            }
        }
        // it must be called after all logic
        return base.DoProcessRequest(context, request, media);
    }
}

:

  • DoProcessRequest, (!)
  • , ,
  • mime " " , , "Content-Disposition" ( Chrome, , "filename-, attachment" )
+1

All Articles