繁体   English   中英

Phonegap - 如何下载文件

[英]Phonegap - How to download files

我正在尝试将信息导出/下载到文件中。 在我的浏览器中它工作正常,但只要我在我的phonegap应用程序中,它只是打开文件作为文本无法保存它,然后无法回到应用程序。 有什么建议么? 顺便说一句,我不是js专家 - 更像是新手!

    function dbError(e) {
        console.log("SQL ERROR");
        console.dir(e);
    }

    function backup(table) {
    var def = new $.Deferred();
    curatio.webdb.db.readTransaction(function(tx) {
        tx.executeSql("select * from "+table, [], function(tx,results) {
            var data = convertResults(results);
            console.dir(data);
            def.resolve(data);
        });
    }, dbError);

    return def;
}

$(document).on("click", "#doBackupBtn", function(e) {
    e.preventDefault();
    console.log("Begin backup process");

    $.when(
        backup("allergies")

    ).then(function(allergies, log) {
        console.log("All done");
        var data = {allergies:allergies}
        var serializedData = JSON.stringify((data), null, 4);
        console.log(serializedData);
        download("Export.csv", serializedData); 

        (function(console){

console.save = function(data, filename){

    if(!data) {
        console.error('Console.save: No data')
        return;
    }

    if(!filename) filename = 'console.json'

    if(typeof data === "object"){
        data = JSON.stringify(data)
    }

    var blob = new Blob([data], {type: 'text/json'}),
        e    = document.createEvent('MouseEvents'),
        a    = document.createElement('a')

    a.download = filename
    a.href = window.URL.createObjectURL(blob)
    a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    a.dispatchEvent(e)
 }
})(console)


    });

});


    function download(filename, content) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
    pom.setAttribute('download', filename);
    pom.click();
    }

    //Generic utility
function convertResults(resultset) {
    var results = [];
    for(var i=0,len=resultset.rows.length;i<len;i++) {
        var row = resultset.rows.item(i);
        var result = {};
        for(var key in row) {
            result[key] = row[key];
        }
        results.push(result);
    }
    return results;
}


        </script>

如果我读得正确,您想要将数据库导出(并导入?)到文件中。

我在Github上的Gist上写了一些代码,我的博客文章也对此进行了解释。 在该代码中,您所要做的就是更改SQL查询和属性。 它将您的数据库导出到基于JSON的文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM