在Phonegap应用程序中使用文件传输插件

时间:2017-03-10 10:41:25

标签: javascript android cordova phonegap-plugins file-transfer

我有两个多星期的时间,我尝试使用文件传输插件在phonegap应用程序中下载文件PDF,但它没有工作!我为此做了一切: - 安装最新版本的phonegap - 安装最新版本的File Transfer插件 这是集成在Javascript界面​​中的代码:

var fileTransfer = new FileTransfer();
fileTransfer.download(
    "http://developer.android.com/assets/images/home/ics-android.png",
    "file://sdcard/ics-android.png",
    function(entry) {
        alert("download complete: " + entry.fullPath);
    },
    function(error) {
        alert("download error source " + error.source);
        alert("download error target " + error.target);
        alert("upload error code" + error.code);
    });

但似乎错了!!!我有一个结果在Android设备中的最后三个警报: - 下载错误源 - 下载错误目标 - 上传错误代码 我该怎么办?!!

2 个答案:

答案 0 :(得分:1)

请求您查看我的github page,其中包含从外部网址下载PDF文件并将其下载到设备的Cordova应用示例。

此示例应用程序在iOS和Android设备上都经过测试。希望它有所帮助。

答案 1 :(得分:0)

根据file transfer plugin documentation,首先您需要创建一个存储远程数据的文件。您的代码应如下所示:

{
    //call this after onDeviceReady event
    ...
    var savePath = cordova.file.externalRootDirectory;
    var fileName = "ics-android.png";
    var url = encodeURI("http://developer.android.com/assets/images/home/ics-android.png");

    downloadFile(savePath, fileName, url);
    ...
}



function downloadFile(savePath, fileName, remoteURL) {
    window.resolveLocalFileSystemURL(savePath, function (dirEntry) {
        console.log('file system open: ' + dirEntry.name);
        createFile(dirEntry, fileName, function (fileEntry) {
            download(remoteURL, fileEntry);
        });
    }, function (err) { alert(err) });
}

function createFile(dirEntry, fileName, callback) {
    // Creates a new file or returns the file if it already exists.
    dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
        callback(fileEntry);
    }, function (err) { alert(err) });

}
function download(remoteURL, fileEntry) {
    var fileURL = fileEntry.toURL();
    var fileTransfer = new FileTransfer();
    fileTransfer.download(
        remoteURL,
        fileURL,
        function (entry) {
            alert("download complete: " + entry.fullPath);
        },
        function (error) {
            alert("download error source " + error.source);
            alert("download error target " + error.target);
            alert("upload error code" + error.code);
        });
}

请注意,对于路径我使用cordova.file.externalRootDirectory,因此您获取文件的root sdcard路径。