【问题标题】:How to download file from url in Ionic 5 without using FileTransfer如何在不使用 FileTransfer 的情况下从 Ionic 5 中的 url 下载文件
【发布时间】:2020-09-05 14:38:29
【问题描述】:

我目前正在开发 Ionic 应用程序并停留在文件下载部分。我看到很多帖子说FileTransfercordova 库现在已被弃用,转而支持 XHR 请求。

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

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

【问题讨论】:

    标签: typescript file ionic-framework ionic-native


    【解决方案1】:

    您可以通过以下步骤实现:

    第 1 步:从 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( () => { });
    }
    
    
    

    第 2 步:使用下载功能将其转换为适当的 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
     }
    );
    
    
    

    第 3 步:使用以下插件将 Blob 数据保存在设备上 https://github.com/apache/cordova-plugin-file

    【讨论】:

    • 当我向服务器发送文件获取请求时出现 CORS 错误。我必须在后端管理 cors 吗?
    • 好的,顺便说一句,您能否分享完整的源代码以供参考。而且我认为我们可以在获取请求中使用reponsetype:blob
    • 这是我的导入,它会抛出错误import { Observable } from 'rxjs';。请显示 Observable 的导入。因为这里它显示不能在 Observable 上使用 .catch。
    • 这段代码无效,也写得不好
    【解决方案2】:

    从另一台服务器下载文件可能会导致恼人的 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);
            })
         }
      }
    }
    

    【讨论】:

    • 这对本机设备来说就像一个魅力,但是对于浏览器来说有什么解决方法吗。
    • 这对我不起作用。没有错误,只是没有发生任何事情
    • @YevheniiBahmutskyi 你在哪里测试?该代码适用于本机设备,您无法使用浏览器对其进行测试。您是否尝试过在调试模式下在设备上进行测试并在终端/命令窗口上打印控制台日志?
    • @ArupBhattacharya 谢谢你的解决方案。我在 ios 设备上使用你的功能,我有这个问题:“ 2021-09-17 11:18:41.526015+0100 F[1617:318799] 错误块 ... 403 2021-09-17 11:18:41.526434+0100 F[1617:318799] 错误块...下载文件时出错”
    【解决方案3】:

    您可以使用window 打开网址。但这将打开一个浏览器并 在那里下载文件。尽管它不漂亮,但它会起作用:

    你的.page.ts:

    function download(url){
      window.open(url, "_blank");
    }
    

    你的.html:

    <a href="javascript:void(0)" (click)="download(yourUrl)">Your file name</>
    

    【讨论】:

      【解决方案4】:

      这是我用于react的解决方案,下载文件MP4并保存在缓存或文档中,Filesystem用于电容器。

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

      【讨论】:

        【解决方案5】:

        您可以简单地使用HttpClient 类(@angular/common/http),如下所示:

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

        您需要的进口商品:

        import { HttpClient } from '@angular/common/http';
        import { File } from '@ionic-native/file/ngx';
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-05-13
          • 2019-07-30
          • 2017-06-28
          • 1970-01-01
          • 2023-03-04
          • 2021-05-26
          • 1970-01-01
          • 2016-03-25
          相关资源
          最近更新 更多