On Bootstrap modal confirm button click ,create an

2019-09-10 10:25发布

问题:

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

回答1:

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