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

Blazor中如何让浏览器将服务器返回的PDF直接下载至下载文件夹

Blazor实现PDF直接下载至浏览器文件夹的方案

方法一:修改服务器端响应头(推荐)

直接在API的GetPDF方法中设置Content-Disposition响应头,强制浏览器识别为下载文件而非在线预览:

// 服务器端API示例代码
public IActionResult GetPDF(Guid ID)
{
    // 假设stream是你获取到的PDF文件流
    var stream = GetYourPDFStream(ID);
    
    // 设置响应头,指定为附件下载,并设置文件名
    Response.Headers.Add("Content-Disposition", $"attachment; filename=document_{ID}.pdf");
    
    return new FileStreamResult(stream, "application/pdf");
}

修改服务器后,更新前端代码(将async void改为async Task,避免Blazor中异常无法捕获的问题):

async Task DownloadDocument(string apiURL, Guid ID)
{
    await JSRuntime.InvokeAsync<string>("open", $"{apiURL}/GetPDF/{ID}", "_blank");
}

此时浏览器会直接触发下载,不会打开新标签页预览PDF。

方法二:前端通过JSInterop处理(无需修改服务器)

如果无法修改服务器端代码,可通过Blazor调用JS,先获取PDF字节流,再创建下载链接触发下载:

1. 更新Blazor前端代码

async Task DownloadDocument(string apiURL, Guid ID)
{
    using var httpClient = new HttpClient();
    var response = await httpClient.GetAsync($"{apiURL}/GetPDF/{ID}");
    response.EnsureSuccessStatusCode();
    
    // 读取PDF字节数组
    var pdfBytes = await response.Content.ReadAsByteArrayAsync();
    
    // 调用JS方法触发下载
    await JSRuntime.InvokeVoidAsync("downloadFile", $"document_{ID}.pdf", pdfBytes);
}

2. 添加JS函数(在wwwroot下的site.js或其他JS文件中)

function downloadFile(filename, byteArray) {
    // 将字节数组转为Blob对象
    const pdfBlob = new Blob([byteArray], { type: 'application/pdf' });
    // 创建临时下载链接
    const downloadUrl = URL.createObjectURL(pdfBlob);
    
    // 创建a标签触发下载
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    
    // 清理资源
    document.body.removeChild(link);
    URL.revokeObjectURL(downloadUrl);
}

注意:确保你的Blazor项目已引用该JS文件(在_Host.cshtml或index.html中添加script标签)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:40:37