Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

javascript - Access files using using Phonegap

I'm trying to work with files on IOS, using Phonegap[cordova 1.7.0]. I read how to access files and read them on the API Documentation of phone gap. But I don't know, when the file is read where will it be written ? & How can I output the text, image, or whatever the text is containing on the iPhone screen?

Here's the code I'm using:

    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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As of Cordova 3.5 (at least), FileReader objects only accept File objects, not FileEntry objects (I'm not sure about prior releases).

Here's an example that will output the contents a local file readme.txt to the console. The difference here from Sana's example is the call to FileEntry.file(...). This will provide the File object needed for the call to the FileReader.readAs functions.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...