elpha01 elpha01 - 2 months ago 12
Javascript Question

Create big downloable file from string variable in HTML/Javascript

I created a js script where I can download a file from a string variable:

window.alert("a");
document.getElementById("export-graphml").innerHTML += "<a id=\"dl\" download=\"graph.graphml\">Download</a>"
window.alert("b");
var vdl = document.getElementById("dl");
window.alert(data.length);
vdl.href = "data:text/plain," + encodeURIComponent(data);


It works very good until my string var (data) isn't too big. When my data is too big the last line of the code makes Chrome and Firefox crash and IE has no reaction.

I didn't find any infos on a possible limit of size anywhere.

If you have any idea thanks to share it.

Answer

Try this (works from 10 ie, and on all modern browsers)

    var createObjectURL = (window.URL || window.webkitURL || {}).createObjectURL || function(){}; 
    var blob = null;
    var content = "byte array or string";
    var mimeString = "application/octet-stream"; 
    window.BlobBuilder = window.BlobBuilder || 
                         window.WebKitBlobBuilder || 
                         window.MozBlobBuilder || 
                         window.MSBlobBuilder;  


    if(window.BlobBuilder){
       var bb = new BlobBuilder();
       bb.append(content);
       blob = bb.getBlob(mimeString);
    }else{
       blob = new Blob([content], {type : mimeString});
    }
    var url = createObjectURL(blob);
    var a = document.createElement("a");
    a.href = url
    a.download = "file.txt";
    a.innerHTML = "download file";
    document.body.appendChild(a);