.PDF and .JPG assets not downloading with JavaScript?

198 views Asked by At

I'd like to have assets available for download on my site via JavaScript. This is the code I currently have:

//Creates an iFrame and adds ID to it to download
var downloadURL = function downloadURL(url) {
    var hiddenIFrameID = 'hiddenDownloader',
        iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;
};

This creates an iframe if none is present, gives the iFrame the ID of "hiddenIFrameID" and downloads it, client side. This currently is working to download .psd and .ai files but cannot interpret the file when it calls to download .jpg or .pdf's. Any advice? Here is the structure of my HTML:

<a onclick="downloadURL('imagepath.jpg');">Download</a>
1

There are 1 answers

7
Sasha On

To force some file (e.g. image, PDF, etc) be downloaded instead of just rendered/displayed by browser:

  1. Either change server-side. The file should be accompanied with Content-Disposition: attachment header. This can be done for example, with .htaccess files.

  2. Or use download attribute of links. For example, <a href="imagepath.jpg" download>Download</a>.

    • You can even initiate download from within script by creating hidden link and calling its click() method.