2018-07-27 19:44:44   Visit  1397

JavaScript在浏览器中把文本保存为文件的方法

经过测试第二种方法可以保存更多的文本不至于卡死

var saveTextAsFile1 = function (text, fileName, success, error) {
    var data = text;
    if (!(text instanceof Array)) {
        data = [text];
    }
    var file = new File(data, fileName);
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (r) {
        var url = reader.result;
        downLoadFile(url, fileName,
            function () {
                success && success();
            }, function () {
                error && error();
            });
    };


}

/**
 * 下载文件
 * @param {string, Array} text 
 * @param {string} fileName 
 * @param {function} success 
 * @param {function} error 
 */
var saveTextAsFile = function (text, fileName, success, error) {
    var data = text;
    if (!(text instanceof Array)) {
        data = [text];
    }
    var urlObject = window.URL || window.webkitURL || window;
    var export_blob = new Blob(data);
    var url = urlObject.createObjectURL(export_blob);
    downLoadFile(url, fileName,
        function () {
            success && success();
        }, function () {
            error && error();
        });
}
©2017 Leechg.com