Explain Codes LogoExplain Codes Logo

Href image link download on click

javascript
download
server-side
browser-compatibility
Anton ShumikhinbyAnton Shumikhin·Aug 5, 2024
TLDR

To promptly trigger a file download when a user clicks on an image, wrap the <img> tag inside an <a> tag and utilize the download attribute:

<a href="path/to/your-image.jpg" download> <img src="path/to/your-image.jpg" alt="Download this fancy image"> </a>

What this does is, rather than navigating to the image, it signals the browser to download the image situated at the href path. To control the name of downloaded file write:

<a href="path/to/your-image.jpg" download="YourChosenName.jpg"> <img src="path/to/your-image.jpg" alt="Download this fancy image"> </a>

PS: The download attribute is exclusive to same-origin URLs, meaning it works just for resources within your domain.

Covering browsers old and new

Older browsers or browsers lacking native support for the download attribute are not left out. Use JavaScript-based solutions or go for a server-side implementation if the download attribute does not perform as expected. Modernizr is a good tool to detect if a browser supports download. Downgrade gracefully to these alternative methods when needed. A PHP script can also be used to set the Content-Disposition headers, prompting the image to download and not just display in the browser.

Dealing with troublesome scenarios

You may run into complex scenarios like forceably downloading from a different domain, or dealing with incorrect MIME types. To ensure a consistent user experience, make use of server-side scripts to set Content-Type and Content-Disposition headers based on actual file contents. Prevent common issues like interrupted downloads or file corruption by 'flushing' or clearing the output buffer before file transmission begins.

Browser Compatibility

For browsers that lack download attribute support mainly Safari and IE, a fallback method has to be crafted. A server-side solution, such as an .htaccess mod_rewrite rule or PHP file-serving script, can bypass these limitations and ensure consistent downloading behaviour across all browsers.

Security Concerns

When dealing with downloads, don't compromise on security. Use server-side measures to prevent autocomplete in your download links and sanitize your paths against unauthorized access or directory traversal attacks. Secure your resources, and most importantly, secure your users!