On Bootstrap modal confirm button click ,create and download file jquery or knockout js

▼魔方 西西 提交于 2019-12-08 09:39:49

问题


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



来源:https://stackoverflow.com/questions/38453699/on-bootstrap-modal-confirm-button-click-create-and-download-file-jquery-or-knoc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!