Download File From Server Into Ionic2 App
Solution 1:
You should use "Transfer" plugin for downloading a file in ionic2
You can install plugin by this command
ionic plugin add cordova-plugin-file-transfer
npm install --save@ionic-native/transfer
and then import it
import { Transfer, FileUploadOptions, TransferObject } from'@ionic-native/transfer';
set constructor
constructor(private transfer: Transfer, private file: File) { }
Then use this function to download file using url
download() {
const url = 'http://www.example.com/file.pdf';
fileTransfer.download(url, this.file.dataDirectory +
'file.pdf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
}
Hope it help you You can also upload a file using this Plugin
Solution 2:
You can use Transfer native plugin for that.
This plugin allows you to upload and download files.
ionic plugin add cordova-plugin-file-transfer
npm install --save@ionic-native/transfer
Solution 3:
First of all. transfer plugin that everyone is referring to here is deprecated. You should never use deprecated plugin if there's alternative.
Gladly, Ionic provides you alternative Native Http plugin
HTTP service has uploadFile and downloadFile methods that you can use to hanlde uploading/downloading of files.
downloadFile method has 4 parameters: url, body, headers, filepath.
In most simple case calling of this method will be like this:
this.nativeHttp.downloadFile(urlWithFile, {}, {}, fileNameToSave)
It returns promise that resolves with FileEntry instance which you can use to read the from file system in future (if you need)
fileNameToSave you can get from File class. Basically, it can be this.file.tempDirectory + fileName or you can pick another directories from file like this.file.dataDirectory + fileName
Again, you should NEVER use deprecated plugins/packages. They are called deprecated for a reason
P.S. if you want then to open downloaded file you can do it with @ionic-native/file-opener plugin like this:
this.file.resolveLocalFilesystemUrl(fileEntry.toURL())
.then((entry: FileEntry) => {
entry.file(meta => {
this.fileOpener.open(fileEntry.toURL(), meta.type)
}, error => {});
})
Solution 4:
you can simply download plugin using
ionic cordova plugin add cordova-plugin-file-transfer
Solution 5:
It should be like below
Add imports
import { Transfer, TransferObject } from '@ionic-native/transfer';
Constructor
constructor(private transfer: Transfer) { }
Create a instance of fileTransfer
const fileTransfer: TransferObject = this.transfer.create();
final code
fileTransfer.download("your URL", "you URLmime tyoe").then((entry) => {
}, (error) => { // handle error });
that's all.
Thanks
Post a Comment for "Download File From Server Into Ionic2 App"