使用Phonegap/jQuery Mobile Android和iOS应用程序下载文件并在本地存储



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

在这一点上,我使用本地存储的json文件来读取数据。

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

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

干杯Johe

使用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);
};
}

我就是这样解决的。首先设置文件路径,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);
});

您可以在一行代码中完成此操作:

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

target_path:可以包含目录(例如:dira/dirb/file.html),并且这些目录将以递归方式创建。

你可以在这里找到这样做的库:

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

我的建议是研究PhoneGap的文件API。我自己没有用过,但它应该能满足你的需求。

新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();
        }
    );
}

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

在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>

参考:-博客文章

最新更新