首页 > 解决方案 > 如何在不使用 FileTransfer 的情况下从 Ionic 5 中的 url 下载文件

问题描述

我目前正在开发 Ionic 应用程序并停留在文件下载部分。我看到很多帖子都表示FileTransfer现在不推荐使用 Cordova 库以支持 XHR 请求。

尽管我看到很多帖子说该库已被弃用,但我找不到任何示例代码(用于从 URL 下载文件)。

谁能建议我在不使用FileTransfer插件的情况下从 url 下载文件的好方法?

标签: typescriptfileionic-frameworkionic-native

解决方案


从另一台服务器下载文件可能会导致恼人的CORS错误,这主要是我们无法控制的。最安全的方法是绕过 Webview 并本地下载文件。你可以使用Native HTTP插件

在 Ionic 4 或更高版本中使用将如下所示:

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

推荐阅读