要实现从.NET Core Web API下载PDF文件并使用Angular进行前端开发,可以按照以下步骤进行操作:
DownloadController
的控制器,添加一个名为DownloadPdf
的动作方法。System.IO.FileStream
打开PDF文件,并使用System.Net.Mime.MediaTypeNames.Application.Pdf
作为内容类型。FileResult
对象,将文件流和内容类型作为参数传递给构造函数。[ApiController]
[Route("api/[controller]")]
public class DownloadController : ControllerBase
{
[HttpGet("pdf")]
public IActionResult DownloadPdf()
{
var filePath = "path_to_pdf_file.pdf";
var contentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
return File(fileStream, contentType);
}
}
DownloadService
的服务,并注入HttpClient
。downloadPdf()
,使用HttpClient
发送GET请求到.NET Core Web API的PDF下载端点,并将响应作为Blob
对象返回。import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DownloadService {
constructor(private http: HttpClient) { }
downloadPdf(): Observable {
const url = 'https://your_api_url/api/download/pdf';
return this.http.get(url, { responseType: 'blob' });
}
}
DownloadService
。downloadPdf()
方法,并订阅返回的Blob
对象。Blob
对象转换为URL,并使用window.open()
打开新的窗口进行下载。import { Component } from '@angular/core';
import { DownloadService } from './download.service';
@Component({
selector: 'app-download',
template: `
`
})
export class DownloadComponent {
constructor(private downloadService: DownloadService) { }
download() {
this.downloadService.downloadPdf().subscribe(blob => {
const url = URL.createObjectURL(blob);
window.open(url);
});
}
}
通过以上步骤,你就可以实现从.NET Core Web API下载PDF文件并使用Angular进行前端开发。请根据实际情况修改代码中的URL、文件路径等参数。