简体   繁体   English

如何从Cordova应用程序中的Byte Array下载任何文件?

[英]How to download any file from Byte Array in Cordova application?

I have a cordova - ionic application. 我有一个cordova - 离子应用程序。 I want to download a file from webservice and the file may be any type(JPG,PDG,DOCX etc). 我想从webservice下载文件,文件可以是任何类型(JPG,PDG,DOCX等)。 I cannot download the file from direct URL. 我无法从直接URL下载文件。 So the app is taking byte array of the file from Webservice. 所以应用程序从Webservice获取文件的字节数组。

Anybody know how to download the file in Mobile from the Byte Array. 任何人都知道如何从字节数组下载Mobile中的文件。 Please help me. 请帮我。

you can use the cordova-plugin-file and the cordova-plugin-file-opener2 plugin. 你可以使用cordova-plugin-file和cordova-plugin-file-opener2插件。

https://github.com/apache/cordova-plugin-file https://github.com/apache/cordova-plugin-file

https://github.com/pwlin/cordova-plugin-file-opener2 https://github.com/pwlin/cordova-plugin-file-opener2

in function with the webservice your code should look like that: 在webservice的功能中,您的代码应如下所示:

var bytes = new Uint8Array(data.d);
app.writePDFToFile(fileName.split(fileName.split, bytes);

and here is teh function forcing the download: 这是强制下载的功能:

writePDFToFile: function (fileName, data) {

try {
    window.resolveLocalFileSystemURL(cordova.file.externalApplicationStorageDirectory, function (directoryEntry) {
        directoryEntry.getFile(fileName, { create: true }, function (fileEntry) {

            fileEntry.createWriter(function (fileWriter) {
                fileWriter.onwriteend = function (e) {

                    //window.open(cordova.file.externalApplicationStorageDirectory + fileName, '_system', 'location=yes');

                    cordova.plugins.fileOpener2.open(cordova.file.externalApplicationStorageDirectory + fileName, 'application/pdf',
                        {
                            error: function (e) {
                                console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
                            },
                            success: function () {
                                console.log('file opened successfully');
                            }
                        }
                    );
                };

                fileWriter.onerror = function (e) {
                    alert(e);
                };

                var blob = new Blob([data], { type: 'application/pdf' });

                fileWriter.write(blob);

            }, function onerror(e) {
                alert(e);
            });
        }, function onerror(e) {

            alert(e);
        });
    }, function onerror(e) {            
        alert(e);
    });

} catch (e) {
     alert(e);
}
},

Hope this will help! 希望这会有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM