2

This is obviously a simplified test but if this works I'm able to do mine.

I want to create a file with string code and download the txt file.

The txt file should have bla bla bla

$("button[id^='downloadTestCase-']").click(function() {
  var code = "bla bla bla"
  var file = new Blob([code], {
    type: 'text/plain'
  });
  window.open(URL.createObjectURL(file));


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" class="btn btn-rounded btn-danger-outline" id="downloadTestCase-Teste50" name="Teste50">Download</button>

2 Answers2

1

You need two separate code blocks, since IE uses msSaveBlob:

document.getElementById('downloadTestCase-Teste50')
    .addEventListener('click', function () {
    var blob = new Blob(
        ['bla bla bla'],
        { type: 'text/plain' }
    );
    var filename = 'result.txt';
    if (window.navigator
        && typeof window.navigator.msSaveOrOpenBlob === 'function') {
        window.navigator.msSaveOrOpenBlob(blob, filename);
    }
    else {
        var objectURL = URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = objectURL;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        URL.revokeObjectURL(objectURL);
    }
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" class="btn btn-rounded btn-danger-outline" id="downloadTestCase-Teste50" name="Teste50">Download</button>
kuujinbo
  • 9,272
  • 3
  • 44
  • 57
0
  1. Create a hidden <a> tag.
  2. Set its href attribute to the blob's URL.
  3. Set its download attribute to the filename.
  4. Click on the <a> tag.

$("button[id^='downloadTestCase-']").click(function() {
  var data = "bla bla bla"
  var fileName = "code"
 saveData(data, fileName);


});


var saveData = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, fileName) {
           var blob = new Blob([data], {type: "text/plain"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-rounded btn-danger-outline" id="downloadTestCase-Teste50" name="Teste50">Download</button>

This is based on an answer on Stack found here

Tony M
  • 741
  • 4
  • 16