ios - Angular 8 - 如何在 iOS 中下载文件

标签 ios angular file download

我无法在 iOS 中下载文件。 这就是我目前所拥有的,代码适用于 Windows 和 Android,使用 Chrome。

对于 iOS,下载选项卡不会弹出。据我所知,这是由于操作系统的一些安全限制造成的。

我正在提供我的代码,很高兴收到一些我可以优化的建议,以便也适用于 iOS。 谢谢

文件服务:

import { HttpClient, HttpHeaders, HttpParams, HttpHeaderResponse, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AppConfigService } from '../app-config.service';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { tap, map } from 'rxjs/operators';
import { Config } from 'protractor';

@Injectable({
  providedIn: 'root'
})
export class DocumentService {

  private dataUrl: string;
  private options: object;
  private getFile: string = '/getFile';
  private documentIndex: string;


  constructor(private http: HttpClient, private appConfigService: AppConfigService, private router: Router) {
    this.dataUrl = appConfigService.config.baseUrl;
  }

  getDocument(documentIndex: string): Observable<Blob> {

    this.documentIndex = documentIndex;
    this.options = {
      headers: new HttpHeaders({
        'X-Ibm-Client-Id': this.appConfigService.config.clientIdDocumentService
      },
      ),
      params: new HttpParams().set('documentIndex', this.documentIndex),
      responseType: 'blob',
      observe: 'response'
    };
    //  return this.http.get(this.dataUrl + this.getFile, this.options).pipe(tap({
    return this.http.get<Blob>(this.dataUrl + this.getFile, this.options).pipe(tap({
      error: (res) => {
        let status = res.status;
        let message = res.statusText;
        this.router.navigate(['/error', status, message]);
      }
    }
    ),
    );
  }
}

组件:

import { Component, OnInit, Input, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { DocumentService } from 'src/app/services/documents.service';
import { saveAs } from "file-saver";


@Component({
  selector: 'app-documents',
  templateUrl: './documents.component.html',
  styleUrls: ['./documents.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class DocumentsComponent implements OnInit {


  documentData: any;
  documentIndex: string;
  header: string;
  @Input() documentsItems: string[];
  imageBlobUrl: string;
  elementBody: any;
  fileUrl: any;
  sanitizer: any;


  constructor(private documentService: DocumentService, private route: ActivatedRoute) { }

  ngOnInit() {

  }

  getDocument(documentIndex: string): void {

    this.documentIndex = documentIndex.split('=')[1];
    this.documentService.getDocument(this.documentIndex).subscribe(documentData => {

      this.documentData = documentData;
      this.header = this.documentData.headers.get('content-disposition');
      this.elementBody = this.documentData['body'];
      const file = new Blob([this.elementBody], {});
      var result = this.header.split(';')[1].trim().split('=')[1].split('"')[1];
      var chartTitle = decodeURI((result));

      var browser = this.getBrowserName();
      console.log(browser);

      const url = window.URL.createObjectURL(file);
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = chartTitle;
      document.body.appendChild(a);
      a.click();

    })

  }

  public getBrowserName() {
    const agent = window.navigator.userAgent.toLowerCase()
    switch (true) {
      case agent.indexOf('edge') > -1:
        return 'edge';
      case agent.indexOf('opr') > -1 && !!(<any>window).opr:
        return 'opera';
      case agent.indexOf('chrome') > -1 && !!(<any>window).chrome:
        return 'chrome';
      case agent.indexOf('trident') > -1:
        return 'ie';
      case agent.indexOf('firefox') > -1:
        return 'firefox';
      case agent.indexOf('safari') > -1:
        return 'safari';
      default:
        return 'other';
    }
  }

  download(base64, fileName) {
    const a = document.createElement("a")
    a.href = base64
    a.style.display = 'none'
    a.download = fileName
    document.body.appendChild(a)
    a.click()
  }


}

查看:

<table>
    <thead>
        <tr>
            <th>Document name</th>
            <th>Download document</th>
        </tr>
    </thead>
    <tbody *ngIf="documentsItems">
        <tr *ngFor="let item of documentsItems">
            <td>{{item.documentName}}</td>
            <td> <button class='button' (click)='getDocument(item.documentIndexInOmniDocs)'>
                Download
            </button></td>
        </tr>
    </tbody>
</table>

最佳答案

某些版本的 safari 不支持下载属性,请在下面检查一些替代方法。

看看这个希望有帮助。

Alternative for 'download' attribute in Safari/iOS

关于ios - Angular 8 - 如何在 iOS 中下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59353212/

相关文章:

ios - 使用 AFNetworking 2 处理响应

ios - NS无效参数异常 : "Unrecognized selector sent to instance"

java - 为什么在 java 中使用 FileReader 时找不到我的文件

ios - 我应该如何在 iOS 7 中使用具有 iOS 6 风格的 UIButtons?

ios - UIButton 仅在按下时显示 tintColor,在正常状态下不显示

javascript - ngClass 始终显示类,无论 Angular 5 中的 bool 值如何

angular - 错误 错误 : unsafe value used in a resource URL context in angular 2

angular - 为来自其他父组件的 div 提供动态 ID

Xcode 4.3.2 显示隐藏文件

python - 有没有办法获取将文件下载到 Python 的原始链接?