Create big downloable file from string variable in HTML/Javascript

久未见 提交于 2020-01-06 01:16:36

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/31656782/create-big-downloable-file-from-string-variable-in-html-javascript

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