'How to download file from url in Ionic 5 without using FileTransfer
I'm currently developing Ionic app now and stuck at file download part. I saw many posts that FileTransfer
cordova library is now deprecated in favor of XHR request.
Even though I saw many posts that the library is deprecated, I can't find any sample code (for downloading file from URL).
Could anyone please suggest me good way to download file from url without using FileTransfer
plugin?
Solution 1:[1]
You can just open the url with window
. But this will open a browser and
download the file there. It will do the trick although it is not pretty:
your.page.ts:
function download(url){
window.open(url, "_blank");
}
your.html:
<a href="javascript:void(0)" (click)="download(yourUrl)">Your file name</>
Solution 2:[2]
This is the solution I used for react, downloading files MP4 and save in the cache or documents, Filesystem is for capacitor.
const bob = await fetch(url).then((x) => x.blob());
const base64 = await convertBlobToBase64(bob);
const resultSaveFile = await Filesystem.writeFile({
data: base64,
path: 'video-edit.mp4',
directory: directory || Directory.Cache,
recursive: true,
});
Solution 3:[3]
You can use simply HttpClient
class (@angular/common/http
) as follow:
const downloadPath = (
this.platform.is('android')
) ? this.file.externalDataDirectory : this.file.documentsDirectory;
let vm = this;
/** HttpClient - @angular/common/http */
this.http.get(
uri,
{
responseType: 'blob',
headers: {
'Authorization': 'Bearer ' + yourTokenIfYouNeed,
}
}
).subscribe((fileBlob: Blob) => {
/** File - @ionic-native/file/ngx */
vm.file.writeFile(downloadPath, "YourFileName.pdf", fileBlob, {replace: true});
});
Imports you will need:
import { HttpClient } from '@angular/common/http';
import { File } from '@ionic-native/file/ngx';
Solution 4:[4]
You can Achieve this in the following steps :
Step 1: A download function to download from URL
downloadFile(path: string, body: Object = {}): Observable<any> {
let headers = {} // add authentication headers and other headers as per your requirement
return this.http.post/get(
`${path}`, body, { headers: headers, withCredentials: true }
)
.catch((err) =>console.log(err))
.map((res:Response) => res)
.finally( () => { });
}
Step 2: Use the download function to convert it into an appropriate Blob.
this.downloadFile(`url`, postData).subscribe(
res => {
let options = { type: ‘filetype’ };
let filename = ‘filename.type’;
Util.createAndDownloadBlobFile(res._body, options, filename);
},
err => {
// show the error
}
);
Step 3: Save the Blob Data on Device using following plugin https://github.com/apache/cordova-plugin-file
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pouria Moosavi |
Solution 2 | alexander ferreras |
Solution 3 | |
Solution 4 | Omkar Tondawalkar |