要使用 .NET 2.0 将 PDF 文件作为二进制文件流式传输到浏览器,您可以遵循以下步骤:
DownloadPdf.ashx
。DownloadPdf.ashx
文件中,编写以下代码:<%@ WebHandler Language="C#" Class="DownloadPdf" %>
using System;
using System.IO;
using System.Web;
public class DownloadPdf : IHttpHandler {
public void ProcessRequest(HttpContext context) {
// 获取 PDF 文件的路径
string pdfPath = context.Server.MapPath("~/path/to/your/pdf/file.pdf");
// 检查文件是否存在
if (!File.Exists(pdfPath)) {
context.Response.StatusCode = 404;
context.Response.StatusDescription = "File not found";
return;
}
// 设置响应头
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("Content-Disposition", "attachment; filename=file.pdf");
context.Response.AddHeader("Content-Length", new FileInfo(pdfPath).Length.ToString());
// 将 PDF 文件作为二进制文件流式传输到浏览器
using (FileStream fs = new FileStream(pdfPath, FileMode.Open, FileAccess.Read)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) {
context.Response.OutputStream.Write(buffer, 0, bytesRead);
}
}
context.Response.Flush();
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
context.Server.MapPath("~/path/to/your/pdf/file.pdf")
替换为您的 PDF 文件的实际路径。DownloadPdf.html
。DownloadPdf.html
文件中,添加以下代码:<!DOCTYPE html>
<html>
<head>
<title>Download PDF</title>
</head>
<body>
<a href="DownloadPdf.ashx">Download PDF</a>
</body>
</html>
注意:在实际应用中,您可能需要根据您的需求对代码进行修改和优化。
领取专属 10元无门槛券
手把手带您无忧上云