Create Text file from String using JS and html5

后端 未结 4 502
感情败类
感情败类 2020-12-29 10:15

i want to create a text file from a string. currently i am using a function which takes an array and makes it into a string then using that string i want to create a local t

相关标签:
4条回答
  • 2020-12-29 10:34

    BlobBuilder is now obsolete. Use this instead:

    https://developer.mozilla.org/en-US/docs/Web/API/Blob#Blob_constructor_example_usage

    0 讨论(0)
  • 2020-12-29 10:46

    Convert your object to a JSON string.

    var json_string = JSON.stringify(object, undefined, 2);
    

    Notes:

    1. If you already have a string, skip the step above.
    2. If you don't want it to be formatted nicely, remove the , undefined, 2.

    Create a download link and click it:

    var link = document.createElement('a');
    link.download = 'data.json';
    var blob = new Blob([json_string], {type: 'text/plain'});
    link.href = window.URL.createObjectURL(blob);
    link.click();
    
    0 讨论(0)
  • 2020-12-29 10:47

    I suggest you use a hidden iframe instead of window.open to make it "a cleaner method"

    and I believe it's text/octet-stream and not text/json to force the download. And as far as I know, you can't set the file name this way.

    However, Chrome (18+ I think) has a download attribute for its <a> tags which you can specify the name of the file along with using blob: for the url.

    0 讨论(0)
  • 2020-12-29 10:50

    i ended up using this code instead. it creates a link to download the url of the file.

         window.URL = window.webkitURL || window.URL;
        window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder ||       window.MozBlobBuilder;
        file = new WebKitBlobBuilder();
        file.append(output); 
        var a = document.getElementById("downloadFile");
        a.hidden = '';
        a.href = window.URL.createObjectURL(file.getBlob('text/plain'));
        a.download = 'filename.txt';
        a.textContent = 'Download file!';
    }
    

    also this way adds less to the website making it a lighter website for slow connections. my html has a empty div in which this appends to.

       <div class ='paginationLIST' id='pagination'></div>
    
    0 讨论(0)
提交回复
热议问题