如何通过C# ASP.NET Web API传输PDF并在Angular端实现预览与下载
实现方案:ASP.NET Web API 发送PDF + Angular 预览&下载
ASP.NET Web API 端实现
编写PDF接口控制器
创建API接口读取服务器本地PDF文件,返回二进制流并指定正确的响应头:
using Microsoft.AspNetCore.Mvc; using System.IO; [Route("api/pdf")] [ApiController] public class PdfController : ControllerBase { private readonly IWebHostEnvironment _hostEnv; public PdfController(IWebHostEnvironment hostEnv) { _hostEnv = hostEnv; } [HttpGet("download")] public IActionResult GetPdfFile() { // 服务器PDF存储路径(示例:wwwroot下的pdfs目录) var pdfFilePath = Path.Combine(_hostEnv.WebRootPath, "pdfs", "document.pdf"); if (!System.IO.File.Exists(pdfFilePath)) { return NotFound("目标PDF文件不存在"); } var fileStream = new FileStream(pdfFilePath, FileMode.Open, FileAccess.Read); // 返回文件流,指定MIME类型为application/pdf,同时设置默认下载文件名 return File(fileStream, "application/pdf", "document.pdf"); } }
Angular 客户端实现
1. 封装PDF请求服务
创建服务处理API请求,指定responseType: 'blob'以接收二进制流:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class PdfService { private apiBaseUrl = 'https://your-api-domain/api/pdf'; constructor(private http: HttpClient) {} getPdfBlob(): Observable<Blob> { return this.http.get(`${this.apiBaseUrl}/download`, { responseType: 'blob' }); } }
2. 组件实现预览&下载功能
在组件中调用服务获取Blob,生成预览URL并提供下载按钮:
组件TS代码
import { Component } from '@angular/core'; import { PdfService } from './pdf.service'; @Component({ selector: 'app-pdf-handler', templateUrl: './pdf-handler.component.html' }) export class PdfHandlerComponent { pdfPreviewUrl: string | null = null; constructor(private pdfService: PdfService) {} // 加载PDF预览 loadPreview() { this.pdfService.getPdfBlob().subscribe(blob => { this.pdfPreviewUrl = URL.createObjectURL(blob); }); } // 下载PDF文件 downloadPdf() { this.pdfService.getPdfBlob().subscribe(blob => { const downloadUrl = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = downloadUrl; link.download = 'document.pdf'; link.click(); // 释放Blob URL资源,避免内存泄漏 URL.revokeObjectURL(downloadUrl); }); } }
组件HTML代码
<div class="pdf-container"> <button (click)="loadPreview()">加载PDF预览</button> <button (click)="downloadPdf()" *ngIf="pdfPreviewUrl">下载PDF</button> <div *ngIf="pdfPreviewUrl" class="pdf-preview"> <h4>PDF预览</h4> <object [data]="pdfPreviewUrl" type="application/pdf" width="100%" height="600px"> 当前浏览器不支持PDF内嵌预览,请点击下载按钮查看文件。 </object> </div> </div>
关键注意事项
- 确保Web API配置了正确的CORS策略,允许Angular域名跨域请求
- 生产环境需添加PDF文件的权限校验,防止未授权访问
- 每次生成Blob URL后,记得调用
URL.revokeObjectURL()释放资源
内容的提问来源于stack exchange,提问作者Himanshu Sharma
相关产品推荐
相关产品推荐

