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

Angular 8-如何在iOS中下载文件,ios,angular,file,download,Ios,Angular,File,Download,我无法在iOS中下载文件。 这就是我目前所拥有的,代码适用于Windows和Android,使用Chrome 对于iOS,下载标签不会弹出。据我所知,这是由于操作系统的一些安全限制 我提供我的代码,将很高兴收到一些建议,我可以优化,以工作的iOS以及。 谢谢 文件服务: import { HttpClient, HttpHeaders, HttpParams, HttpHeaderResponse, HttpResponse } from '@angular/common/http'; impo

我无法在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]);
      }
    }
    ),
    );
  }
}
从'@angular/common/http'导入{HttpClient,HttpHeaders,HttpParams,httpheaderrresponse,HttpResponse};
从“rxjs”导入{Observable};
从“../app config.service”导入{AppConfigService};
从“@angular/core”导入{Injectable};
从'@angular/Router'导入{Router};
从“rxjs/operators”导入{tap,map};
从“量角器”导入{Config};
@注射的({
providedIn:'根'
})
导出类文档服务{
私有dataUrl:string;
私人选择:客体;
私有getFile:string='/getFile';
私有文档索引:字符串;
构造函数(专用http:HttpClient,专用appConfigService:appConfigService,专用路由器:路由器){
this.dataUrl=appConfigService.config.baseUrl;
}
getDocument(documentIndex:string):可观察{
this.documentIndex=documentIndex;
此选项={
标题:新的HttpHeaders({
“X-Ibm-Client-Id”:this.appConfigService.config.clientIdDocumentService
},
),
params:new-HttpParams().set('documentIndex',this.documentIndex),
responseType:'blob',
观察:“回应”
};
//返回this.http.get(this.dataUrl+this.getFile,this.options)({
返回this.http.get(this.dataUrl+this.getFile,this.options)({
错误:(res)=>{
让状态=res.status;
让消息=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()
  }


}

从'@angular/core'导入{Component,OnInit,Input,ViewEncapsulation};
从'@angular/router'导入{ActivatedRoute};
从'src/app/services/documents.service'导入{DocumentService};
从“文件保存程序”导入{saveAs};
@组成部分({
选择器:“应用程序文档”,
templateUrl:'./documents.component.html',
样式URL:['./documents.component.css'],
封装:视图封装。无
})
导出类文档组件实现OnInit{
文件资料:任何;
文档索引:字符串;
标题:字符串;
@Input()文档站点:字符串[];
imageBlobUrl:字符串;
元素体:任何;
fileUrl:any;
消毒剂:任何;
构造函数(私有documentService:documentService,私有路由:ActivatedRoute){}
恩戈尼尼特(){
}
getDocument(documentIndex:string):无效{
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((结果));
var browser=this.getBrowserName();
控制台日志(浏览器);
const url=window.url.createObjectURL(文件);
常量a=document.createElement('a');
a、 style.display='none';
a、 href=url;
a、 下载=图表标题;
文件.正文.附件(a);
a、 单击();
})
}
公共getBrowserName(){
const agent=window.navigator.userAgent.toLowerCase()
开关(真){
案例代理。indexOf('edge')>-1:
返回“边缘”;
case agent.indexOf('opr')>-1&&!!(窗口)。opr:
返回“歌剧”;
case agent.indexOf('chrome')>-1&&!!(窗口)。chrome:
返回“chrome”;
案件代理人indexOf('trident')>-1:
返回“ie”;
case agent.indexOf('firefox')>-1:
返回“firefox”;
案例代理。indexOf('safari')>-1:
返回‘狩猎’;
违约:
返回“其他”;
}
}
下载(base64,文件名){
常量a=document.createElement(“a”)
a、 href=base64
a、 style.display='none'
a、 下载=文件名
document.body.appendChild(a)
a、 单击()
}
}
视图:


文件名
下载文件
{{item.documentName}
下载

有些电子版safari不支持下载属性,下面有一些替代选项

看看这个,希望对你有帮助

<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>