You probably all have had the experience where you click on an image link and instead of downloading the image it is previewed in a new browser window.
The web wouldn’t be the web if you couldn’t control this behavior. By adding the download attribute on your a tag you can trigger a download instead of a navigation:
More info: https://www.w3schools.com/tags/att_a_download.asp
Unfortunately this doesn’t always work. Firefox and Chrome 65+ only support same-origin download links as a security measure.
More info: https://caniuse.com/#feat=download (see "Known issues" tab)
As most of our images are hosted on a separate CDN, we bumped on exactly this issue.
To fix this in cross-origin scenario’s, the web server that hosts the image needs to send a Content-Disposition
HTTP header. If this header is found, the download attribute will be honored in all situations.
In ASP.NET Core this is easily achieved by using one of the overloads of the File method on the ControllerBase class:
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName);
If you specify a fileDownloadName a Content-Disposition header will be added to the response containing:
Content-Disposition: attachment; filename="fileDownloadName"