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

Andrew Fletcher11 Feb 2025
Webpack build process and theme automation improvements
The Drupal theme configuration has undergone recent changes made to the Webpack configuration, SCSS and JavaScript handling, and automation of updates to the orw.libraries.yml file in the custom Drupal theme. These changes are designed to improve the build process, enhance maintainability, and...
Andrew Fletcher22 Jan 2025
Removing a missing module in Drupal
Occasionally, a Drupal site may display a warning about a module being "Missing or invalid." This issue occurs when a module is marked as installed in the configuration but is no longer present in the file system. A common example is the `fakeobjects` module, which is associated with CKEditor 4 and...