How to download file from url in Ionic 5 without using FileTransfer How to download file from url in Ionic 5 without using FileTransfer typescript typescript

How to download file from url in Ionic 5 without using FileTransfer


Downloading files from another server may cause annoying CORS error which is mostly beyond our control. The safest way is to bypass the Webview and download the file natively. You may use Native HTTP plugin

Use in Ionic 4 or above will look like:

import { Component } from '@angular/core';import { HTTP } from '@ionic-native/http/ngx';import { File } from '@ionic-native/file/ngx';        @Component({   selector: 'app-home',   templateUrl: './you-file.html',   styleUrls: ['./your-file.scss'],})export class HomePage {    constructor(private nativeHTTP: HTTP, private file: File) {}             private downloadFileAndStore() {        //        const filePath = this.file.dataDirectory + fileName;                          // for iOS use this.file.documentsDirectory                this.nativeHTTP.downloadFile('your-url', {}, {}, filePath).then(response => {           // prints 200           console.log('success block...', response);        }).catch(err => {            // prints 403            console.log('error block ... ', err.status);            // prints Permission denied            console.log('error block ... ', err.error);        })     }  }}


You can just open the url with window. But this will open a browser anddownload 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</>


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,      });