javascriptjqueryfile-ioforce-download

Force Download an Image Using Javascript


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.


Solution

  • 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>