0

I have a bootstrap modal( bootbox ), on which confirm action, i want to create a file which contains some numbers and download the file as a text file.

I have already referred Create a file in memory for user to download, not through server but its not helpful in my case.

Here is the code :

bootbox.confirm("Item not found! Do you want to download the text file?", (yes) => {
    var items = response.itemNumbers;
    this.href = "data:text/plain;charset=UTF-8," + encodeURIComponent(items);
});

I have tried this as well :

bootbox.confirm("item not found! Do you want to download the text file?", (yes) => {

    var itemNumbers = response.itemNumbers;
    var textFile = null;

    var data = new Blob([itemNumbers], { type: 'text/plain' });

    // deleting old text file
    if (textFile !== null) {
        window.URL.revokeObjectURL(textFile);
    }

    textFile = window.URL.createObjectURL(data);

    var link = $(textFile).attr("href");

    document.location.href = link;

});

EDIT : When I run this, first code runs and nothing happens. Second gives error about Blob conversion : Syntax error, unrecognized expression: blob:http%3A//localhost%3A51876/028f2122-1646-4b2e-ae2c-2a1b588fdd8d

Community
  • 1
  • 1
Vishal_Kotecha
  • 481
  • 5
  • 19
  • I assume the missing `"` in the beginning of *Item not found!* string is just a copy/paste typo. What happens when you run this, what part isn't working? Does the confirm event not fire at all or is it just the download that fails? – kb. Jul 19 '16 at 08:56
  • yes it was a typo. I corrected- thanks. I have updated the question as well. please take a look @kb. – Vishal_Kotecha Jul 19 '16 at 09:02
  • Could you paste the Blob error, and also verify the contents of itemNumbers with a `console.log(itemNumbers)`? Also where is response declared, in the parent scope of the `bootbox.confirm()`? – kb. Jul 19 '16 at 09:11
  • I have updated the question with error. when I change the last three lines to : `textFile = window.URL.createObjectURL(data); document.location.href = textFile` page is redirected to another page and I can see the numbers on that blank page. please suggest – Vishal_Kotecha Jul 19 '16 at 09:22
  • 1
    It seems you can't force a download with `document.location.href` but rather needs to go via an event/action, this is one variant http://stackoverflow.com/questions/19327749/javascript-blob-filename-without-link – kb. Jul 19 '16 at 09:32

1 Answers1

0

Got it! thanks @kb. for helping. The link you provided had the answer. Just posting here for future visitors: below code would create a file which contains "abcd,wxyz" and prompt for download :

    var items = "abcd,wxyz";
    var json = JSON.stringify(items);
    var blob = new Blob([json], {type: "octet/stream"});
    var url  = window.URL.createObjectURL(blob);
    window.location.assign(url);

reference : JavaScript blob filename without link

Community
  • 1
  • 1
Vishal_Kotecha
  • 481
  • 5
  • 19