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 Fletcher04 Apr 2025
Managing .gitignore changes
When working with Git, the .gitignore file plays a critical role in controlling which files and folders are tracked by version control. Yet, many developers are unsure when changes to .gitignore take effect and how to manage files that are already being tracked. This uncertainty can lead to...
Andrew Fletcher26 Mar 2025
How to fix the ‘Undefined function t’ error in Drupal 10 or 11 code
Upgrading to Drupal 10.4+ you might have noticed a warning in their code editor stating “Undefined function ‘t’”. While Drupal’s `t()` function remains valid in procedural code, some language analysis tools — such as Intelephense — do not automatically recognise Drupal’s global functions. This...
Andrew Fletcher17 Mar 2025
Upgrading to PHP 8.4 challenges with Drupal contrib modules
The upgrade from PHP 8.3.14 to PHP 8.4.4 presents challenges for Drupal 10.4 websites, particularly when dealing with contributed modules. While Drupal core operates seamlessly, various contrib modules have not yet been updated to accommodate changes introduced in PHP 8.4.x. This has resulted in...