获取phonegap中的设备绝对路径?

时间:2014-04-26 10:01:18

标签: android ios cordova

我使用Phonegap 3.3.0,之前我使用的是2.5.0,其中entry.fullPath将为设备提供完整路径。 这些路径通常看起来像

/var/mobile/Applications/<application UUID>/Documents/path/to/file  (iOS)
/storage/emulated/0/path/to/file                                    (Android)

因为该方法不推荐使用entry.toURL()方法来获取路径。此方法现在将返回表单的文件系统URL

cdvfile://localhost/persistent/path/to/file

在我的应用程序中,我将URL传递给Native函数,并从本机传递文件。但是,如果我将路径传递给Native,则iOS无法检测到该文件。相同如果我对绝对路径进行硬编码,应用程序会检测到该文件。

如何使用fileSystem URL以本机或任何其他方法访问文件以获取设备的绝对路径?

提前致谢。

3 个答案:

答案 0 :(得分:7)

toURL()方法或nativeURL属性应返回所需的结果:

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
    console.log("fileSystem.root.toURL()="+fileSystem.root.toURL());
    console.log("fileSystem.root.toInternalURL()="+fileSystem.root.toInternalURL());
    console.log("fileSystem.root.nativeURL="+fileSystem.root.nativeURL);
}, function(){
    alert("fails!");
});

使用cordova 3.5,iPad模拟器中的输出为:

fileSystem.root.toURL()=file:///Users/myuser/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/1717CB5F-4032-45C7-8CA2-342502447F36/Documents/
fileSystem.root.toInternalURL()=cdvfile://localhost/persistent/
fileSystem.root.nativeURL=file:///Users/myuser/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/1717CB5F-4032-45C7-8CA2-342502447F36/Documents/

...在Android模拟器(Genymotion)中是:

fileSystem.root.toURL()=file:///storage/emulated/0/ 
fileSystem.root.toInternalURL()=cdvfile://localhost/persistent/ 
fileSystem.root.nativeURL=file:///storage/emulated/0/ 

答案 1 :(得分:0)

document.addEventListener("deviceready", onDeviceReady, false);

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

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

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

        // save the file system for later access
    console.log(fileSystem.root.fullPath);
    window.rootFS = fileSystem.root;
}

function downloadImage(url, fileName){
    var ft = new FileTransfer();
    ft.download(
        url,
        window.rootFS.fullPath + "/" + fileName,
        function(entry) {
            console.log("download complete: " + entry.fullPath);

        },
        function(error) {
            console.log("download error" + error.code);
        }
    );
}

答案 2 :(得分:0)

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);

function gotFS(fileSystem) {
  alert("entered gotFS: " + fileSystem.root.toURL);
}