【问题标题】:Angular 8 - How to download file in iOSAngular 8 - 如何在 iOS 中下载文件
【发布时间】:2019-12-16 08:53:19
【问题描述】:

我无法在 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>

【问题讨论】:

    标签: ios angular file download


    【解决方案1】:

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

    看看这个希望它有帮助。

    Alternative for 'download' attribute in Safari/iOS

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-08
      • 2021-01-05
      • 2014-09-13
      • 1970-01-01
      • 2018-02-19
      • 2020-05-20
      • 2021-04-23
      • 1970-01-01
      相关资源
      最近更新 更多