Force Download an Image Using Javascript Force Download an Image Using Javascript javascript javascript

Force Download an Image Using Javascript


You need to use server-side scripting for this. Search on stackoverflow.

Alternately, your server might allow you to alter headers dynamically via configuration.

Apache solution with mod_headers

Place your downloadable images in a directory. Inside this directory, create a .htaccess file with the following contents:

SetEnvIf Request_URI "([^/]+\.jpg)$" REQUESTED_IMAGE_BASENAME=$1SetEnvIf Request_URI "([^/]+\.png)$" REQUESTED_IMAGE_BASENAME=$1Header set Content-Disposition "attachment; filename=\"%{REQUESTED_IMAGE_BASENAME}e\"" env=REQUESTED_IMAGE_BASENAME

Test Request:

HEAD /test/Water%20lilies.jpg HTTP/1.1Host: localhost

Test Response:

HTTP/1.1 200 OKDate: Sat, 23 Jul 2011 09:03:52 GMTServer: Apache/2.2.17 (Win32)Last-Modified: Thu, 23 Aug 2001 14:00:00 GMTETag: "26000000017df3-14752-38c32e813d800"Accept-Ranges: bytesContent-Length: 83794Content-Disposition: attachment; filename="Water lilies.jpg"Content-Type: image/jpeg

HTML5 Solution

You can use the HTML5 download attribute on anchors:

<p>Example 1<br>   <a href="http://dummyimage.com/600x400/000/fff.png" download>Download this image</a></p><p>Example 2<br>   <a href="http://dummyimage.com/600x400/000/fff.png" download="alternate-filename.png"><img       src="http://dummyimage.com/150x100/000/fff.png"></a></p>