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

牧云@^-^@ 提交于 2019-12-11 12:43:44

问题


I have a cordova - ionic application. I want to download a file from webservice and the file may be any type(JPG,PDG,DOCX etc). I cannot download the file from direct URL. So the app is taking byte array of the file from Webservice.

Anybody know how to download the file in Mobile from the Byte Array. Please help me.


回答1:


you can use the cordova-plugin-file and the cordova-plugin-file-opener2 plugin.

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

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

in function with the webservice your code should look like that:

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!



来源:https://stackoverflow.com/questions/35402715/how-to-download-any-file-from-byte-array-in-cordova-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!