You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular 9中基于ng2-pdf-viewer实现上传PDF文件的预览功能

完全没问题!你可以利用浏览器自带的URL.createObjectURL() API,把用户上传的PDF文件转换成一个临时本地URL,直接传给ng2-pdf-viewer的[src]属性就能实现预览了。下面是具体的实现步骤:

1. 编写模板代码(HTML)

先添加上传文件的输入框,再保留你现有的pdf-viewer组件,记得加个条件渲染避免初始空值报错:

<!-- 文件上传控件,限制仅允许PDF文件 -->
<input type="file" accept=".pdf" (change)="onFileSelected($event)">

<!-- PDF预览组件,只有当临时URL存在时才渲染 -->
<pdf-viewer 
  [src]="tmpPdfUrl" 
  [render-text]="true" 
  [original-size]="false" 
  [zoom]="1"
  *ngIf="tmpPdfUrl"
></pdf-viewer>

2. 实现组件逻辑(TypeScript)

在你的Angular组件类里,处理文件选择事件并生成临时URL,同时别忘了清理资源防止内存泄漏:

import { Component, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnDestroy {
  tmpPdfUrl: string | null = null;

  onFileSelected(event: Event): void {
    const fileInput = event.target as HTMLInputElement;
    // 确保用户选择了文件,且是PDF
    if (fileInput.files?.length && fileInput.files[0].type === 'application/pdf') {
      const selectedFile = fileInput.files[0];
      
      // 先释放之前的临时URL,避免内存堆积
      if (this.tmpPdfUrl) {
        URL.revokeObjectURL(this.tmpPdfUrl);
      }
      
      // 生成指向本地文件的临时URL
      this.tmpPdfUrl = URL.createObjectURL(selectedFile);
    }
  }

  // 组件销毁时清理临时URL,释放浏览器资源
  ngOnDestroy(): void {
    if (this.tmpPdfUrl) {
      URL.revokeObjectURL(this.tmpPdfUrl);
    }
  }
}

几个关键注意点

  • 这个临时URL是浏览器在内存中生成的,仅在当前页面会话有效,刷新页面后就会失效,非常适合预览场景。
  • 一定要在组件销毁时调用URL.revokeObjectURL(),不然会造成浏览器内存泄漏。
  • 用accept=".pdf"和文件类型判断,能避免用户上传非PDF文件导致预览失败。

内容的提问来源于stack exchange,提问作者Bob Mahindra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 05:52:38