文件预览功能/文件流前端展示

文章展示了如何通过HTTP接口获取文件流,将其转换为Blob对象,从而实现图片、PDF、Word和Excel等文件的在线预览。主要涉及的技术包括HTTP的响应类型设置、Blob构造函数以及预览不同类型的文件方式。
摘要由CSDN通过智能技术生成

文件预览展示

接口请求,处理返回文件流转换为 Blob对象

  // 预览图片 或者pdf格式文件
  getViewImg(id: string) {
    return this.http.get(`/workflow/attachment/viewImg/${id}`, {
      observe: 'response',
      responseType: 'blob'
    });
  }
    // 预览word文件或Excel文件
  getViewFile(id: string) {
    return this.http.get(`/workflow/attachment/view/${id}`, {
      observe: 'response',
      responseType: 'blob'
    })
  }

预览实现ts代码

  // 附件预览
  handlePreviewClick(item: any) {
    if (!this.isPreviewModalVisible) {
      this.changeIsSpinning.emit(true);
      this.isPreviewModalVisible = true;
      this.id = item.id;
      this.isImage = this.handleiIsImage(item.attachmentName);
      this.isPDF = this.handleiIsPDF(item.attachmentName);
      let type = (this.isImage || this.isPDF) ? 'getViewImg' : 'getViewFile';
      this.service[type](this.id).subscribe(
        async (res: any) => {
          if (this.isImage) {
            const downloadUrl = window.URL.createObjectURL(res.body);
            this.fileHTML = downloadUrl;
          } else if (this.isPDF) {
            let newBlob = new window.Blob([res.body], { type: 'application/pdf;charset-UTRF-8' })
            const downloadUrl = window.URL.createObjectURL(newBlob);
            this.fileHTML = downloadUrl;
          } else {
            this.fileHTML = await res.body.text();
          }
          this.changeIsSpinning.emit(false);
        }, () => {
          this.messageService.error('加载失败');
          this.isPreviewModalVisible = false;
          this.changeIsSpinning.emit(false);
        }
      )
    }
  }

弹窗代码

<nz-modal *ngIf="fileHTML" [nzStyle]="{ top: '50px' }" [nzWidth]="1100" [nzBodyStyle]="bodyStyle" [nzContent]="modalContent" [(nzVisible)]="isVisible" nzTitle="预览"
  [nzFooter]="modalFooter" (nzOnCancel)="handleCancel()">
  <ng-template #modalContent>
    <div *ngIf="!isImage&&!isPDF" [innerHtml]="fileHTML"></div>
    <img *ngIf="isImage" [src]="fileHTML" alt="加载失败" style="max-width:1044px"/>
    <iframe *ngIf="isPDF" [src]="fileHTML" alt="加载失败" style="width:1044px;height: 510px;"></iframe>
  </ng-template>
  <ng-template #modalFooter>
    <button nz-button nzType="primary" (click)="handleOk()">确定</button>
  </ng-template>
</nz-modal>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值