通过JS(PhoneGap)存储来自GET请求的数据

时间:2012-06-06 18:31:56

标签: javascript cordova get

我想从Amazon S3服务器获取数据(audiofiles), 并将其存储在便携式设备的本机文件系统中。

我将使用PhoneGap(PhoneGap - Wiki - Filesystem)来存储数据, 但是如何制作GET请求并处理返回的文件并将其保存到文件系统?

1 个答案:

答案 0 :(得分:3)

以下一组功能可能有所帮助:

function onDeviceReady() {
    console.log("device is ready");
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function fail() {
    console.log("failed to get filesystem");
}

function gotFS(fileSystem) {
    console.log("got filesystem");

    // for later use
    window.fileSystem = fileSystem;

    // Create your app specific dir here
    fileSystem.root.getDirectory(".myapp", {
        create: true,
        exclusive: false
    },
    dirReady, fail);
}

function dirReady(entry) {
    // for later use
    window.appRootDir = entry;
    console.log(JSON.stringify(window.appRootDir));

    var fileToDownload = "http://....";
    var fileName = "file name";
    downloadToAppRoot(fileToDownload, fileName,
    function() {},
    function() {});
}

function downloadToAppRoot(url, name, success, failure) {
    var fileTransfer = new FileTransfer();
    var filePath = window.appRootDir.fullPath + "/" +  name;
    fileTransfer.download(
    url,
    filePath,
    function(entry) {
        console.log("download complete: " + entry.fullPath);
        success(entry);
    },
    function(error) {
        console.log("download error source " + error.source);
        if (failure) failure(error);
    }
    );
}

PhoneGap拥有广泛的文件系统API来创建目录和文件。 有关详细信息,请查看PhoneGap文档here