Cordova应用程序:如何获取文件的实际路径

Cordova App : How to get the actual path of file

本文关键字:文件 路径 获取 应用程序 何获取 Cordova      更新时间:2023-11-02

我正在使用Cordova制作android和iOS应用程序,现在我想检查目录中是否已经存在文件。

首先,我从服务器下载文件,并使用下面的代码将其保存在本地

$scope.downloadFile = function(){
        alert(cordova.file.dataDirectory)
        var fileTransfer = new FileTransfer();
        var uri = encodeURI("http://example.com/files/th/001.mp3");
        var downloadPath = cordova.file.dataDirectory+'001.mp3'; // ANDROID
        fileTransfer.download(
            uri,
            downloadPath,
            function(entry) {
                $scope.savepath = entry.toInternalURL();
                alert("download complete: " + entry.toURL());
                alert('saved at : '+entry.toInternalURL());
            },
            function(error) {
                alert("download error source " + error.source);
                alert("download error target " + error.target);
                alert("upload error code" + error.code);
            },
            false,
            {
                headers: {
                    "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
                }
            }
        );
    }//End DownloadFile

我想使用checkIfFileExists(path)方法检查文件是否已经存在

function checkIfFileExists(path){
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
            //alert('result: '+JSON.stringify(fileSystem.root))
            fileSystem.root.getFile(path, { create: false }, fileExists, fileDoesNotExist);
        }, getFSFail); //of requestFileSystem
    }
    function fileExists(fileEntry){
        alert("File " + fileEntry.fullPath + " exists!");
    }
    function fileDoesNotExist(){
        alert("file does not exist");
    }
    function getFSFail(evt) {
        console.log(evt.target.error.code);
    }

我在手机上检查了一下,文件已经保存到Android/data/com.myname.myappname/file/001.mp3

但问题是每当我使用类似的路径时,代码总是显示文件不存在

cordova.file.dataDirectory+'001.mp3';

cdvfile://localhost/persistent/files/001.mp3

'cdvfile://localhost/files/001.mp3'

所以我想问一下,我需要使用的真实路径来检查文件是否存在。

请给我任何建议。

谨致问候。

是否需要使用或CheckFileExists?你可以尝试使用Phonegap的FileReader方法吗?

var reader = new FileReader();
var fileSource = cordova.file.dataDirectory+'001.mp3'
reader.onloadend = function(evt) {
if(evt.target.result == null) {
   // Null? You still have a problem: file doesn't exist.
} else {
    // Otherwise the file exists. 
}         
};
//Check if the file exists
reader.readAsDataURL(fileSource);