Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  159] [ 1]  / answers: 1 / hits: 102403  / 13 Years ago, fri, july 22, 2011, 12:00:00

I want to know if there is any way to make a script using Javascript/jQuery to download (open a download dialog) a image so the browser won't just show it.


More From » jquery

 Answers
13

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=$1
SetEnvIf Request_URI ([^/]+.png)$ REQUESTED_IMAGE_BASENAME=$1
Header set Content-Disposition attachment; filename=%{REQUESTED_IMAGE_BASENAME}e env=REQUESTED_IMAGE_BASENAME


Test Request:



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


Test Response:



HTTP/1.1 200 OK
Date: Sat, 23 Jul 2011 09:03:52 GMT
Server: Apache/2.2.17 (Win32)
Last-Modified: Thu, 23 Aug 2001 14:00:00 GMT
ETag: 26000000017df3-14752-38c32e813d800
Accept-Ranges: bytes
Content-Length: 83794
Content-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>




[#91048] Thursday, July 21, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pierce

Total Points: 315
Total Questions: 103
Total Answers: 89

Location: Svalbard and Jan Mayen
Member since Mon, Jun 7, 2021
3 Years ago
;