javascript - 使用Phonegap访问文件

标签 javascript iphone ios5 cordova

我正在尝试使用Phonegap [cordova 1.7.0]在IOS上处理文件。
我阅读了如何访问文件,并在电话间隙的API Documentation上阅读了它们。但我不知道,何时读取文件将在哪里写入? &如何在iPhone屏幕上输出文本,图像或任何文本?

这是我正在使用的代码:

    function onDeviceReady() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function gotFS(fileSystem) {
    fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
}

function gotFileEntry(fileEntry) {
    fileEntry.file(gotFile, fail);
}

function gotFile(file){
    readDataUrl(file);
    readAsText(file);
}

function readDataUrl(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("Read as data URL");
        console.log(evt.target.result);
    };
    reader.readAsDataURL(file);
}

function readAsText(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("Read as text");
        console.log(evt.target.result);
    };
    reader.readAsText(file);
}

function fail(evt) {
    console.log(evt.target.error.code);
}

最佳答案

从Cordova 3.5(至少)开始,FileReader对象仅接受File对象,而不接受FileEntry对象(我不确定以前的版本)。

这是一个将本地文件readme.txt的内容输出到控制台的示例。与Sana的示例的区别在于对FileEntry.file(...)的调用。这将提供调用File函数所需的FileReader.readAs对象。

function readFile() {
    window.requestFileSystem(window.LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
        fileSystem.root.getFile('readme.txt', 
            {create: false, exclusive: false}, function(fileEntry) {
                fileEntry.file(function(file) {
                    var reader = new window.FileReader();
                    reader.onloadend = function(evt) {console.log(evt.target.result);};
                    reader.onerror = function(evt) {console.log(evt.target.result);};
                    reader.readAsText(file);
                }, function(e){console.log(e);});
            }, function(e){console.log(e);});
    }, function(e) {console.log(e);});
}

关于javascript - 使用Phonegap访问文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10462561/

相关文章:

iphone - 如何实现无边框的 UISearchBar

ios - 大小适合 : is returning different Values iOS 5 and iOS 6

ios - 动画 UIView 的内容不接收触摸事件

javascript - switch语句好像没有落空

javascript - 从 setTimeout 调用生成器函数

javascript - 准备数组以便在闭包中进行排序

javascript - 如何以编程方式添加到可变嵌套对象?

iphone - UITableView 图像 - 保存两个图像或调整大小?

iphone - 为已发布的 iPhone 应用程序迁移 Core Data 数据库的步骤

javascript - 禁用webapp的ios5通知中心下拉