13

Using the following lines of code I am able to download a file in the response of a Ajax call in Firefox, Chrome, Opera. However in IE the href attribute download is not supported. Therefore the below does not work in IE.

HTML:

 <div class="fRight" style="margin-left:5px; margin-rigth:5px" >
    <input type="button" value="Request File"  id = "chReqFileBtn"  onclick = "handleClick"/>
    <a href="#" id="challengeReqFileAnchor" style="visibility: hidden"></a>
 </div>

JavaScript:

function handleClick()
{
    var code = $('#code').val();
    var quantity = $('#quantity').val();

    var req = $.ajax(
    {
        'type': 'POST',
        'url' : $apiBasePath+'config/challenge-file',
         contentType : 'application/json',
        'data': JSON.stringify({'code':code, 'quantity':quantity}),
        'success':function(response, status, xhr)
        {
            var code = xhr.getResponseHeader('Operation-Code');

            var anch = $('#challengeReqFileAnchor');
            anch.attr(
            {
                "download" : 'request.bin',
                "href" : "data:text/plain," + response       
            });
            anch.get(0).click();
        },
        'error': function(request,status,errorThrown) 
        {
           ......
        }
    });
    $pendingReqs.push(req);  
}

What options would I have to accomplish the same behavior in IE as well?

sampathsris
  • 21,564
  • 12
  • 71
  • 98
steve
  • 594
  • 4
  • 10
  • 23
  • Why not let the server handle this? What is the purpose of the ajax call? – Prinzhorn Aug 04 '14 at 14:48
  • 4
    Sometimes a lower-tech approach is better - because it's not just IE that will have problems! Consider saving the AJAX result on the server (or simply making it a normal HTTP request in the first place) and having the server set appropriate `content-disposition` headers. – Niet the Dark Absol Aug 04 '14 at 14:48
  • But if you absolutely want this in-browser: https://github.com/ChenWenBrian/FileSaver.js#examples – Prinzhorn Aug 04 '14 at 14:49
  • On the server side I set the specific headers to enforce donwload ,but since this is ajax it has no effect.I do it in ajax because I also need to execute extra code in the response . – steve Aug 04 '14 at 15:02
  • 1
    my downloader script works in IE10+: http://danml.com/js/download.js it uses msSaveBlob for IE10 compat... – dandavis Aug 11 '14 at 02:48
  • @steve why don't you create something like my fiddle: http://jsfiddle.net/GuyT/r8oknrko/1/ – GuyT Aug 12 '14 at 09:40

6 Answers6

28

Download attribute is NOT supported in IE and iOS Safari

enter image description here

IE<10:

Command SaveAs using execCommand can do the trick, by making element's contents downloadable.

Cons:

  • Problems in some versions of IE running on Win7 [I don't know if it's fixed Here]
  • Need a DOM element to contain data

IE>=10

Using msSaveBlob, it's a method that allows to save Blob or File by sending this headers:

Content-Length: <blob.size>
Content-Type: <blob.type>
Content-Disposition: attachment;filename=<defaultName>
X-Download-Options: noopen

Check Saving files locally using Blob and msSaveBlob

Cons:

  • Need a to define a Blob

Other browsers

If you don't want to implement all that by yourself, there is a nice library FileSaver.js to save generated files on client side. It supports Firefox, Chrome, Chrome for Android, IE 10+, Opera and Safari. For IE<10 there is a fork of the library that adds saveTextAs to save text files (.htm, .html, .txt)

Cross browsers solution

A server side script that receives filename, data, meme type then send the file with the header Content-Disposition: attachment; filename=FILENAME

Community
  • 1
  • 1
Issam Zoli
  • 2,724
  • 1
  • 21
  • 35
4

I think this is related to the anch.get(0).click(); not supported by all browser specially for hidden anchors, so you may try following code instead,

anch.get(0).show().focus().click().hide();
Dharmesh Patel
  • 1,881
  • 1
  • 11
  • 12
3

IE does not support neither navigating to a data URI nor the download attribute. You can use navigator.msSaveBlob to save file for IE 10+.
You can check window.navigator.msSaveBloband write IE specific Code otherwise use existing code to save file.
You can check following link for more details: Saving files locally using Blob and msSaveBlob

Amjad Aziz
  • 103
  • 8
2

IE does not support download tag.

There's an ugly hack you can use however.

  • Create an invisible iframe:

    <iframe id="dummy" style="display:none; visibility:hidden"></iframe>
    
  • Write your data to the iframe's document:

    var ifd = document.getElementById('dummy').contentDocument;
    ifd.open('text/plain', 'replace');
    ifd.write('whatever you want to be in the file');
    ifd.close();
    
  • Use execCommand to save the file (actually, to prompt the save as dialog):

    ifd.execCommand('SaveAs', true, 'request.bin');
    

Note that execCommand does not work in IE11. I know it is nearly impossible to detect the browser perfectly correctly. However you can try this as a backup routine if file saving fails in your code.

Community
  • 1
  • 1
sampathsris
  • 21,564
  • 12
  • 71
  • 98
1

My javascript version for download file from IE11 with BOM and charset for excel:

$.post('/cup-frontend/requestthewholelist',
    {ipAddressList: validIpAddressListAsString},   // add custom http variables
    function (returnedData) {                      // success return
        var BOM = "\uFEFF";                        // byte order mark for excel

        if (navigator.msSaveBlob) {                // ie block
            console.log("found msSaveBlob function - is't IE")
            var blobObject = new Blob([BOM + returnedData], {type: ' type: "text/csv; charset=utf-8"'});
            window.navigator.msSaveOrOpenBlob(blobObject, "cup_database.csv");
        }
        else {                                     // non-ie block
            console.log("not found msSaveBlob function - is't not IE")
            var a = window.document.createElement('a');
            a.setAttribute('href', 'data:text/plain; charset=utf-8,' + encodeURIComponent(BOM + returnedData));
            a.setAttribute('download', 'example.csv');
            a.click();
        }

    }).fail(function () {
    console.log('post error')
});
d0wn
  • 121
  • 4
0

Finally, after doing hours of research I found some answer which really worked for me. Following approach worked for me.

if (navigator.msSaveBlob) { // For IE
   return navigator.msSaveBlob(blobObj, fileName);
}

In below line

navigator.msSaveBlob(blobObj, fileName)

function msSaveBlob saves the file to the disk. Parameter blobObj is the object which needs to be saved with a given name in parameter fileName

For more information please visit following link: MDN Webdocs Mozilla

vikasrajputin
  • 81
  • 1
  • 5