50

From the following code I'm creating a dynamic anchor tag which downloads a file. This code works well in Chrome but not in IE. How can I get this working

<div id="divContainer">
    <h3>Sample title</h3>
</div>
<button onclick="clicker()">Click me</button>

<script type="text/javascript">

    function clicker() {
        var anchorTag = document.createElement('a');
        anchorTag.href = "http://cdn1.dailymirror.lk/media/images/finance.jpg";
        anchorTag.download = "download";
        anchorTag.click();


        var element = document.getElementById('divContainer');
        element.appendChild(anchorTag);
    }

</script>
EricLaw
  • 56,563
  • 7
  • 151
  • 196
Nipuna
  • 6,846
  • 9
  • 64
  • 87

9 Answers9

35

Internet Explorer does not presently support the Download attribute on A tags.

See http://caniuse.com/download and http://status.modern.ie/adownloadattribute; the latter indicates that the feature is "Under consideration" for IE12.

EricLaw
  • 56,563
  • 7
  • 151
  • 196
31

In my case, since there's a requirement to support the usage of IE 11 (version 11.0.9600.18665), I ended up using the solution provided by @Henners on his comment:

// IE10+ : (has Blob, but not a[download] or URL)
if (navigator.msSaveBlob) {
    return navigator.msSaveBlob(blob, fileName);
}

It's quite simple and practical.

Apparently, this solution was found on the Javascript download function created by dandavis.

António Ribeiro
  • 4,129
  • 5
  • 32
  • 49
  • 2
    I tried this and get blob is undefined. Can you explain how to define blob and what to put in it. I just have the URL of the file. Is there a way to load a file into a blob from the URL? – boilers222 Sep 19 '17 at 12:58
  • Perhaps [this answer](https://stackoverflow.com/questions/34000412/how-do-i-convert-url-to-blob-with-javascript-or-jquery) can help you to achieve the conversion you want. Afterwards, you just need to trigger the download as mentioned in my answer. – António Ribeiro Sep 19 '17 at 14:36
15

Old question, but thought I'd add our solution. Here is the code I used on my last project. It's not perfect, but it passed QA in all browsers and IE9+.

downloadCSV(data,fileName){
  var blob = new Blob([data], {type:  "text/plain;charset=utf-8;"});
  var anchor = angular.element('<a/>');

  if (window.navigator.msSaveBlob) { // IE
    window.navigator.msSaveOrOpenBlob(blob, fileName)
  } else if (navigator.userAgent.search("Firefox") !== -1) { // Firefox
    anchor.css({display: 'none'});
    angular.element(document.body).append(anchor);

    anchor.attr({
      href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
      target: '_blank',
      download: fileName
    })[0].click();

    anchor.remove();
  } else { // Chrome
    anchor.attr({
      href: URL.createObjectURL(blob),
      target: '_blank',
      download: fileName
    })[0].click();
  }
}

Using the ms specific API worked best for us in IE. Also note that some browsers require the anchor to actually be in the DOM for the download attribute to work, whereas Chrome, for example, does not. Also, we found some inconsistencies with how Blobs work in various browsers. Some browsers also have an export limit. This allows the largest possible CSV export in each browser afaik.

Kevin
  • 1,195
  • 12
  • 14
5

As of build 10547+, the Microsoft Edge browser is now supporting the download attribute on a tags.

<a href="download/image.png" download="file_name.png">Download Image</a>

Edge features update: https://dev.windows.com/en-us/microsoft-edge/platform/changelog/desktop/10547/

a[download] standard: http://www.w3.org/html/wg/drafts/html/master/links.html#attr-hyperlink-download

MWOJO
  • 336
  • 3
  • 7
3

This code fragment allows saving blob in the file in IE, Edge and other modern browsers.

var request = new XMLHttpRequest();
request.onreadystatechange = function() {

    if (request.readyState === 4 && request.status === 200) {

        // Extract filename form response using regex
        var filename = "";
        var disposition = request.getResponseHeader('Content-Disposition');
        if (disposition && disposition.indexOf('attachment') !== -1) {
            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            var matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
        }

        if (window.navigator.msSaveOrOpenBlob) { // for IE and Edge
            window.navigator.msSaveBlob(request.response, filename);
        } else {
            // for modern browsers
            var a = document.createElement('a');
            a.href = window.URL.createObjectURL(request.response);
            a.download = filename;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
        }
    }

    button.disabled = false;
    dragArea.removeAttribute('spinner-visible');
    // spinner.style.display = "none";

};
request.open("POST", "download");
request.responseType = 'blob';
request.send(formData);

For IE and Edge use: msSaveBlob

Alexey
  • 7,127
  • 9
  • 57
  • 94
1

Use my function

It bind your atag to download file in IE

function MS_bindDownload(el) {
    if(el === undefined){
        throw Error('I need element parameter.');
    }
    if(el.href === ''){
        throw Error('The element has no href value.');
    }
    var filename = el.getAttribute('download');
    if (filename === null || filename === ''){
        var tmp = el.href.split('/');
        filename = tmp[tmp.length-1];
    }
    el.addEventListener('click', function (evt) {
        evt.preventDefault();
        var xhr = new XMLHttpRequest();
        xhr.onloadstart = function () {
            xhr.responseType = 'blob';
        };
        xhr.onload = function () {
            navigator.msSaveOrOpenBlob(xhr.response, filename);
        };
        xhr.open("GET", el.href, true);
        xhr.send();
    })
}
0

Append child first and then click

Or you can use window.location= 'url' ;

Voonic
  • 4,667
  • 3
  • 27
  • 58
  • 1
    If I append child first and then click. It redirects to the image rather than downloading – Nipuna Aug 24 '13 at 07:59
0

As mentioned in earlier answer , download attribute is not supported in IE . As a work around, you can use iFrames to download the file . Here is a sample code snippet.

function downloadFile(url){
    var oIframe = window.document.createElement('iframe');
    var $body = jQuery(document.body);
    var $oIframe = jQuery(oIframe).attr({
        src: url,
        style: 'display:none'
    });
    $body.append($oIframe);

}
May13ank
  • 548
  • 2
  • 9
  • 24
  • 1
    How is this supposed to work? I have an iframe appended right before the closing `

    ` tag with a source of my file.

    – Dusty Jun 23 '15 at 18:27
  • If the content-disposoition in the header is attachment , it will try to download instead of rendering it in iFrame. – May13ank Jun 24 '15 at 09:47
  • header('Content-Disposition: attachment; filename="some filename"'); – May13ank Jun 24 '15 at 09:47
0

I copied the code from here and updated it for ES6 and ESLint and added it to my project.

You can save the code to download.js and use it in your project like this:

import Download from './download'
Download('/somefile.png', 'somefile.png')

Note that it supports dataURLs (from canvas objects), and more... see https://github.com/rndme for details.

Simon Hutchison
  • 2,949
  • 1
  • 33
  • 32