【问题标题】:Download files and store them locally with Phonegap/jQuery Mobile Android and iOS Apps使用 Phonegap/jQuery Mobile Android 和 iOS 应用程序下载文件并将其存储在本地
【发布时间】:2011-09-19 00:16:28
【问题描述】:

我编写了一个 jQuery Mobile 应用程序,并用 Phonegap 将它打包到 iOS 和 Android 应用程序中。

此时我正在使用本地存储的 json 文件来读取数据。

我想不时通过从服务器下载更新的 json 文件来更新这些 json 文件。

如何从服务器获取json并将json文件存储到Android和iOS的本地文件系统中?

干杯 乔赫

【问题讨论】:

  • 我们以字符串形式获取数据,然后存储到字节数组中以形成 pdf。如果您能提供代码 sn-p 用于在 iPad 中保存生成的 pdf,我将非常高兴,然后查看相同的内容。几周以来我们一直在努力寻找解决方法。虽然我们能够使用 android,但不能用于 ios :(

标签: android ios cordova jquery-mobile


【解决方案1】:

使用FileTransfer.download,这里是一个例子:

function downloadFile(){

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, 
    function onFileSystemSuccess(fileSystem) {
        fileSystem.root.getFile(
        "dummy.html", {create: true, exclusive: false}, 
        function gotFileEntry(fileEntry) {
            var sPath = fileEntry.fullPath.replace("dummy.html","");
            var fileTransfer = new FileTransfer();
            fileEntry.remove();

            fileTransfer.download(
                "http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
                sPath + "theFile.pdf",
                function(theFile) {
                    console.log("download complete: " + theFile.toURI());
                    showLink(theFile.toURI());
                },
                function(error) {
                    console.log("download error source " + error.source);
                    console.log("download error target " + error.target);
                    console.log("upload error code: " + error.code);
                }
            );
        }, fail);
    }, fail);
};
}

【讨论】:

  • 感谢您提供这段令人惊叹的代码。它拥有我需要的一切......好吧,除了最后引用的失败变量。如果您打算使用它,只需将 fail 定义为如下函数: function fail(error) { console.log(error.code); }
  • 我如何强制它不使用外部存储并将其存储在www目录下创建的abc文件夹中?
  • 上面的代码最初发布在这里:gist.github.com/nathanpc/2464060,你可以看到需要几个额外的函数(fail 和 showLink)才能使代码正常工作。
  • 这里的dummy.html是什么..??
  • 此代码不再适用于较新版本的 Cordova API。他们改变了一点,看到这个话题 - stackoverflow.com/questions/21756274/… 另外,创建虚拟不是真的必要,你可以用 fileSystem.root.toNativeURL()
【解决方案2】:

我就是这样解决的。首先设置文件路径,Android和iOS不同

var file_path;
function setFilePath() {
    if(detectAndroid()) {   
        file_path = "file:///android_asset/www/res/db/";
        //4 Android
    } else {
        file_path = "res//db//";
        //4 apache//iOS/desktop
    }
}

然后,我将与应用程序一起预打包的 JSON 文件加载到本地浏览器存储中。像这样:

localStorage["my_json_data"] = loadJSON(file_path + "my_json_data.json");

function loadJSON(url) {
    return jQuery.ajax({
        url : url,
        async : false,
        dataType : 'json'
    }).responseText;
}

如果我想更新我的数据。我从服务器获取新的 JSON 数据并将其推送到本地存储中。如果服务器在不同的域上,大多数时候都是这种情况,你必须进行 JSONP 调用(查看JSONP 上的 jQuery 文档)。 我是这样做的:

$.getJSON(my_host + 'json.php?function=' + my_json_function + '&callback=?', function (json_data) {
    //write to local storage
    localStorage["my_json_data"] = JSON.stringify(json_data);

});

【讨论】:

  • 是的,如果您编写/使用 xml 解析器。
  • 这是一种不好的方法,因为它同时使用 async:false 和跨域请求。您应该使用 phonegaps FileTransfer.download 而不是 docs.phonegap.com/en/2.0.0/…
  • 我同意@Blowsie 的观点,因为您正在使用实现此功能的框架,您不必采取变通办法。
  • 您是否建议使用 File API 通过 phonegap 进行 ajax 调用,我一直在尝试了解,但我是第一次看到有人建议不要使用 jQuery 吗?你能解释一下吗?
【解决方案3】:

你可以在一行代码中做到这一点:

new FileManager().download_file('http://url','target_path',Log('downloaded success'));

target_path:可以包含目录(例如:dira/dirb/file.html),目录会递归创建。

您可以在此处找到执行此操作的库:

https://github.com/torrmal/cordova-simplefilemanagement

【讨论】:

    【解决方案4】:

    我的建议是查看PhoneGap 的File API。我自己没有用过,但它应该可以满足您的需求。

    【讨论】:

    • 我尝试了文件 api 但无法使其工作。示例代码有人吗?
    • @JoheGreen 你的问题解决了吗?您可以发布示例代码吗?
    【解决方案5】:

    新 Cordova 的更新答案

    function downloadFile(url, filename, callback, callback_error) {
        var fileTransfer = new FileTransfer();
        fileTransfer.download(url,
            cordova.file.dataDirectory + "cache/" + filename,
            function (theFile) {
                console.log("download complete: " + theFile.toURL());
                if (callback)
                    callback();
            },
            function (error) {
                console.log("download error source " + error.source);
                console.log("download error target " + error.target);
                console.log("upload error code: " + error.code);
                if (callback_error)
                    callback_error();
            }
        );
    }
    

    【讨论】:

      【解决方案6】:

      要下载和显示文件,请遵循示例代码。

      在 index.html 中的 </head> 标记上方包含给定的代码

      < script type = "text/javascript" charset = "utf-8" >
        // Wait for Cordova to load
        document.addEventListener("deviceready", onDeviceReady, false);
      // Cordova is ready
      function onDeviceReady() {
        alert("Going to start download");
        downloadFile();
      }
      
      function downloadFile() {
        window.requestFileSystem(
          LocalFileSystem.PERSISTENT, 0,
          function onFileSystemSuccess(fileSystem) {
            fileSystem.root.getFile(
              "dummy.html", {
                create: true,
                exclusive: false
              },
              function gotFileEntry(fileEntry) {
                var sPath = fileEntry.fullPath.replace("dummy.html", "");
                var fileTransfer = new FileTransfer();
                fileEntry.remove();
                fileTransfer.download(
                  "http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
                  sPath + "theFile.pdf",
                  function(theFile) {
                    console.log("download complete: " + theFile.toURI());
                    showLink(theFile.toURI());
                  },
                  function(error) {
                    console.log("download error source " + error.source);
                    console.log("download error target " + error.target);
                    console.log("upload error code: " + error.code);
                  }
                );
              },
              fail);
          },
          fail);
      }
      
      function showLink(url) {
        alert(url);
        var divEl = document.getElementById("deviceready");
        var aElem = document.createElement("a");
        aElem.setAttribute("target", "_blank");
        aElem.setAttribute("href", url);
        aElem.appendChild(document.createTextNode("Ready! Click To Open."))
        divEl.appendChild(aElem);
      }
      
      function fail(evt) {
        console.log(evt.target.error.code);
      }
      </script>
      

      参考:-Blog Post

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 2013-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多