Skip to main content

In a site I'm working at the moment, we need to download high resolution images for media groups.  How do you force a href to download rather than the default display in the browser?

The code I've written to manage the paragraph is

{% block paragraph %}
	<div{{attributes.addClass(classes)}}>
		{% block content %}
			<div class="g-0">
				<div class="row align-items-top g-10">
					<div class="d-none d-sm-block">
						{% set media_image = content.field_paragraph_high_resolution[0]['#media'].field_media_image %}
						{% set alt = media_image.alt %}
						{% set uri = media_image.entity.uri.value %}
						{% set res_filesize = media_image.entity.filesize.value %}
						{% set uri_path = uri|replace({'public://' : '/'}) %}
						<a href="/sites/default/files{{ uri_path }}" alt="{{ alt }}">{{ alt }}</a> ({{ filesize.bytesToSize(res_filesize) }})
					</div>
					{{ content.field_paragraph_text }}
				</div>
			</div>
		{% endblock %}
	</div>
{% endblock paragraph %}

Now, in most browsers, by clicking on the link will open the file directly in the browser.  However, the change to download is quite simple.  In the href tag you only need to add the word download.  So the href line becomes

						<a href="/sites/default/files{{ uri_path }}" alt="{{ alt }}" download>{{ alt }}</a> ({{ filesize.bytesToSize(res_filesize) }})

The download attribute works in all modern browsers, including MS Edge, but not Internet Explorer.  But not many are still using IE.  Whilst they're still around we don't need to allow for them.  However, a handy note is that in the most recent versions of Chrome, you cannot download cross-origin files (they have to be hosted on the same domain).

Related articles