Forcing Browser Downloads for Images Using Client-Side Programming
Background
When clicking on an Excel sheet or other downloadable files, browsers typically initiate the download process seamlessly. However, there is a need to replicate this behavior for image files specifically.
Implementing Image Downloads
Using client-side programming alone, you can achieve image downloads as follows:
document.onclick = function (e) { e = e || window.event; var element = e.target || e.srcElement; if (element.innerHTML == "Image") { var name = element.nameProp; var address = element.href; saveImageAs1(element.nameProp, element.href); return false; // Prevent default action and stop event propagation } else return true; }; function saveImageAs1(name, address) { if (confirm('you wanna save this image?')) { window.win = open(address); setTimeout('win.document.execCommand("SaveAs")', 100); setTimeout('win.close()', 500); } }
This code intercepts click events on the image element and prompts the user to save it using a Save As dialog box.
Case of Excel Downloads
In the case of Excel downloads, browsers handle the download process internally. They identify the file type based on the MIME type and trigger the appropriate download behavior without any additional programming.
HTML5 'download' Attribute
However, newer browsers support the 'download' attribute for elements, which provides a more convenient way to initiate image downloads:
<a href="http://localhost:55298/SaveImage/demo/abc.jpg" download>Image</a>
This attribute prompts the browser to download the image with the provided filename or the original filename, if not specified. Note that cross-origin downloads using this method are no longer supported as of 2018 due to security concerns.
The above is the detailed content of How to Force Browser Downloads for Images Using Client-Side Programming?. For more information, please follow other related articles on the PHP Chinese website!