无法使用 FileTransfer 在 Cordova 和 Ionic 中下载文件

Unable to download file in Cordova and Ionic with FileTransfer

我想在我的 ionic 应用程序上从 internet/server 下载一个文件。我一直在使用文件传输插件来尝试实现相同的目的,但文件没有被下载。

我从插件获得了成功回调,但是如果我尝试从 fileOpener2 插件打开文件,我得到一个错误,指出文件不存在。我检查了我 phone 的所有文件存储空间,但找不到。 PFB 我使用的代码:

var fileTransfer = new FileTransfer();

var imguri = "http://cdn.wall-pix.net/albums/art-space/00030109.jpg";
var targetPath = cordova.file.dataDirectory + "testImage.jpg";
fileTransfer.download(
imguri,
targetPath,
function(entry) {
    console.log("download complete - Internal URL: " + entry.toInternalURL());
    console.log("download complete - Full Path: " + entry.fullPath);

                            $cordovaFileOpener2.open(entry.fullPath, 'image/jpeg').then(function() {
                        // file opened successfully
                        console.log("File opened successfully!");
                    }, function(err) {
                        // An error occurred. Show a message to the user
                        console.log(JSON.stringify(err));
                    });



},
function(error) {
    console.log("download error source " + error.source);
    console.log("download error target " + error.target);
    console.log("download error code" + error.code);
},
false,
{
    headers: {
        "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
    }
}
);

在 $cordovaFileOpener2.open 中,如果我将 entry.toInternalURL 作为参数,我会收到此错误 -> 无法找到包含 /data/data/com.echidna.foodreview/files/testImage 的已配置根目录.jpg

在 $cordovaFileOpener2.open 中,如果我给 entry.fullPath 作为参数,我会得到这个错误 ->{"status":9,"message":"File not found" }

我在文件管理器中搜索了 testImage.jpg 文件,但未找到该文件。那应该是文件没有下载,那么成功回调是怎么触发的呢?

问题似乎是 Android 6.0 及更高版本中的应用程序所需的新用户权限。文件插件不请求用户进行存储访问。这必须首先由应用程序请求,并且可以由另一个插件处理。有一些插件可以解决这个问题,但我正在使用 https://github.com/NeoLSN/cordova-plugin-android-permission,这对我有用!

因此,在下载之前,请检查您是否对存储有写权限。如果不这样做,则请求权限(检查和请求权限由上面 link 中的插件处理)。获得访问权限后,下载任何你想要的文件!

干杯!

而不是

 file.dataDirectory 

将文件存储为私有文件并且不允许您的文件管理器读取它

使用

 file.externalDataDirectory 

将文件存储为 public 并允许其他应用打开它

请不要与 externalDataDirectory 混淆,因为(SD 卡)它仅使用您的设备内部存储器