跳至页脚内容
使用IRONPDF

如何在ASP.NET Core中使用C#上传和下载PDF文件

在 ASP.NET Core 中上传和下载 PDF 文件需要处理二进制数据、管理控制器操作,以及(可选地)在存储或交付之前在服务器端处理文档。 借助IronPDF ,您不仅可以进行简单的文件存储,还可以添加水印、从 HTML 生成 PDF,并将处理后的文档返回给用户,所有操作都可以在您现有的 MVC 流程中完成。本指南将引导您使用 .NET 10 和 C# 逐步构建完整的上传/下载工作流。

如何在 ASP.NET Core 项目中安装 IronPDF?

在编写任何上传或下载逻辑之前,请使用 NuGet 包管理器或 .NET CLI 将 IronPDF 添加到您的项目中。 在包管理器控制台中使用 Install-Package IronPdf,或运行以下 CLI 命令来搭建一个新的 MVC 项目并一次性添加所有必需的包。

dotnet new mvc -n PdfManager --framework net10.0
cd PdfManager
dotnet add package IronPdf
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet new mvc -n PdfManager --framework net10.0
cd PdfManager
dotnet add package IronPdf
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design
SHELL

安装完成后,IronPDF 提供以下功能:ChromePdfRenderer,用于从 HTML 生成 PDF;PdfDocument,用于加载和操作现有文件;以及一系列编辑工具,包括水印、图章和数字签名。 您可以查看完整的IronPDF NuGet 包页面,了解版本历史记录和兼容性说明。

项目设置

Program.cs 添加存储路径常量,并将您的 ApplicationDbContext 注册到依赖注入容器。 在编写任何 PDF 特定逻辑之前,您的项目结构将包含 Controllers/PdfController.csModels/PdfFileModel.csData/ApplicationDbContext.cs

如何创建用于PDF存储的数据库模型?

任何 PDF 上传系统的基础都是一个映射到数据库表的模型类。 以下 C# 记录捕获了基本字段——文件名、内容类型、原始二进制数据和上传时间戳。

public class PdfFileModel
{
    public int Id { get; set; }
    public string FileName { get; set; } = string.Empty;
    public string ContentType { get; set; } = "application/pdf";
    public byte[] FileData { get; set; } = Array.Empty<byte>();
    public DateTime UploadedDate { get; set; } = DateTime.UtcNow;
}
public class PdfFileModel
{
    public int Id { get; set; }
    public string FileName { get; set; } = string.Empty;
    public string ContentType { get; set; } = "application/pdf";
    public byte[] FileData { get; set; } = Array.Empty<byte>();
    public DateTime UploadedDate { get; set; } = DateTime.UtcNow;
}
Public Class PdfFileModel
    Public Property Id As Integer
    Public Property FileName As String = String.Empty
    Public Property ContentType As String = "application/pdf"
    Public Property FileData As Byte() = Array.Empty(Of Byte)()
    Public Property UploadedDate As DateTime = DateTime.UtcNow
End Class
$vbLabelText   $csharpLabel

FileData 将 PDF 存储为二进制大对象 (BLOB)。 这种方法将文档保留在数据库中,使备份更简单,查询更直接。 对于高容量场景或大型文件,可以考虑仅在数据库中存储文件路径,并将二进制文件写入云存储桶,例如Azure Blob StorageAmazon S3

配置 Entity Framework Core

通过向你的模型添加 DbSet<PdfFileModel> 属性,将模型注册到 EF Core 中:

using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options) { }

    public DbSet<PdfFileModel> PdfFiles { get; set; }
}
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options) { }

    public DbSet<PdfFileModel> PdfFiles { get; set; }
}
Imports Microsoft.EntityFrameworkCore

Public Class ApplicationDbContext
    Inherits DbContext

    Public Sub New(options As DbContextOptions(Of ApplicationDbContext))
        MyBase.New(options)
    End Sub

    Public Property PdfFiles As DbSet(Of PdfFileModel)
End Class
$vbLabelText   $csharpLabel

运行 dotnet ef migrations add InitialCreate,然后运行 dotnet ef database update 来创建模式。 Entity Framework Core 会自动将 byte[] 映射到 SQL Server 中的 varbinary(max) 列或 SQLite 中的 BLOB 列 -- 无需手动编写 SQL。

如何在 ASP.NET Core 控制器中上传 PDF 文件?

处理上传的控制器操作从使用 enctype="multipart/form-data" 的 HTML 表单接收 IFormFile 参数。 该操作将流读取到 MemoryStream 中,将其转换为字节数组,并通过 Entity Framework Core 持久化结果。

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

public class PdfController : Controller
{
    private readonly ApplicationDbContext _context;

    public PdfController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpPost]
    public async Task<IActionResult> Upload(IFormFile file)
    {
        if (file is null || file.Length == 0)
            return BadRequest("No file selected.");

        if (!file.ContentType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase))
            return BadRequest("Only PDF files are accepted.");

        using var stream = new MemoryStream();
        await file.CopyToAsync(stream);

        var pdfFile = new PdfFileModel
        {
            FileName = Path.GetFileName(file.FileName),
            ContentType = file.ContentType,
            FileData = stream.ToArray(),
            UploadedDate = DateTime.UtcNow
        };

        _context.PdfFiles.Add(pdfFile);
        await _context.SaveChangesAsync();

        return RedirectToAction(nameof(Index));
    }

    public async Task<IActionResult> Index()
    {
        var files = await _context.PdfFiles
            .Select(f => new { f.Id, f.FileName, f.UploadedDate })
            .ToListAsync();
        return View(files);
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

public class PdfController : Controller
{
    private readonly ApplicationDbContext _context;

    public PdfController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpPost]
    public async Task<IActionResult> Upload(IFormFile file)
    {
        if (file is null || file.Length == 0)
            return BadRequest("No file selected.");

        if (!file.ContentType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase))
            return BadRequest("Only PDF files are accepted.");

        using var stream = new MemoryStream();
        await file.CopyToAsync(stream);

        var pdfFile = new PdfFileModel
        {
            FileName = Path.GetFileName(file.FileName),
            ContentType = file.ContentType,
            FileData = stream.ToArray(),
            UploadedDate = DateTime.UtcNow
        };

        _context.PdfFiles.Add(pdfFile);
        await _context.SaveChangesAsync();

        return RedirectToAction(nameof(Index));
    }

    public async Task<IActionResult> Index()
    {
        var files = await _context.PdfFiles
            .Select(f => new { f.Id, f.FileName, f.UploadedDate })
            .ToListAsync();
        return View(files);
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.EntityFrameworkCore
Imports System.IO
Imports System.Threading.Tasks

Public Class PdfController
    Inherits Controller

    Private ReadOnly _context As ApplicationDbContext

    Public Sub New(context As ApplicationDbContext)
        _context = context
    End Sub

    <HttpPost>
    Public Async Function Upload(file As IFormFile) As Task(Of IActionResult)
        If file Is Nothing OrElse file.Length = 0 Then
            Return BadRequest("No file selected.")
        End If

        If Not file.ContentType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase) Then
            Return BadRequest("Only PDF files are accepted.")
        End If

        Using stream As New MemoryStream()
            Await file.CopyToAsync(stream)

            Dim pdfFile As New PdfFileModel With {
                .FileName = Path.GetFileName(file.FileName),
                .ContentType = file.ContentType,
                .FileData = stream.ToArray(),
                .UploadedDate = DateTime.UtcNow
            }

            _context.PdfFiles.Add(pdfFile)
            Await _context.SaveChangesAsync()
        End Using

        Return RedirectToAction(NameOf(Index))
    End Function

    Public Async Function Index() As Task(Of IActionResult)
        Dim files = Await _context.PdfFiles _
            .Select(Function(f) New With {f.Id, f.FileName, f.UploadedDate}) _
            .ToListAsync()
        Return View(files)
    End Function
End Class
$vbLabelText   $csharpLabel

验证上传的文件

处理内容前务必验证内容类型。 检查 file.ContentType 可防止用户意外上传非 PDF 内容。 为了进行更严格的验证,读取流的前四个字节并验证 PDF 魔数(%PDF)。 您还应该强制执行最大文件大小(一般文档工作流程为 10 MB),方法是在复制流之前检查 file.Length

触发此操作的 HTML 表单需要两个属性:method="post"enctype="multipart/form-data"。 如果没有指定编码类型,浏览器会将文件名作为纯文本而不是二进制内容发送。 添加一个 <input type="file" name="file" accept=".pdf" /> 元素,并在表单标签内添加一个指向 /Pdf/Upload 的提交按钮。

 如何使用 IronPDF 在 ASP .NET C# 中上传和下载 PDF 文件:图片 1 - 显示上传的 PDF 的用户界面

如何在保存前给上传的PDF文件添加水印?

在存储之前对服务器端文件进行处理是IronPDF 水印功能最实用的用途之一。 您可以在每个传入文档到达数据库之前,为其添加"机密"标签、公司徽标或"草稿"通知。

[HttpPost]
public async Task<IActionResult> UploadWithWatermark(IFormFile file)
{
    if (file is null || file.Length == 0)
        return BadRequest("No file selected.");

    using var stream = new MemoryStream();
    await file.CopyToAsync(stream);
    byte[] originalBytes = stream.ToArray();

    // Load the uploaded file into IronPDF
    var pdf = new IronPdf.PdfDocument(originalBytes);

    // Apply an HTML watermark centered on every page
    pdf.ApplyWatermark(
        "<h2 style='color:red;opacity:0.4'>CONFIDENTIAL</h2>",
        rotation: 45,
        opacity: 60,
        verticalAlignment: IronPdf.Editing.VerticalAlignment.Middle,
        horizontalAlignment: IronPdf.Editing.HorizontalAlignment.Center
    );

    var pdfFile = new PdfFileModel
    {
        FileName = Path.GetFileName(file.FileName),
        ContentType = "application/pdf",
        FileData = pdf.BinaryData,
        UploadedDate = DateTime.UtcNow
    };

    _context.PdfFiles.Add(pdfFile);
    await _context.SaveChangesAsync();

    return RedirectToAction(nameof(Index));
}
[HttpPost]
public async Task<IActionResult> UploadWithWatermark(IFormFile file)
{
    if (file is null || file.Length == 0)
        return BadRequest("No file selected.");

    using var stream = new MemoryStream();
    await file.CopyToAsync(stream);
    byte[] originalBytes = stream.ToArray();

    // Load the uploaded file into IronPDF
    var pdf = new IronPdf.PdfDocument(originalBytes);

    // Apply an HTML watermark centered on every page
    pdf.ApplyWatermark(
        "<h2 style='color:red;opacity:0.4'>CONFIDENTIAL</h2>",
        rotation: 45,
        opacity: 60,
        verticalAlignment: IronPdf.Editing.VerticalAlignment.Middle,
        horizontalAlignment: IronPdf.Editing.HorizontalAlignment.Center
    );

    var pdfFile = new PdfFileModel
    {
        FileName = Path.GetFileName(file.FileName),
        ContentType = "application/pdf",
        FileData = pdf.BinaryData,
        UploadedDate = DateTime.UtcNow
    };

    _context.PdfFiles.Add(pdfFile);
    await _context.SaveChangesAsync();

    return RedirectToAction(nameof(Index));
}
Imports System.IO
Imports System.Threading.Tasks
Imports Microsoft.AspNetCore.Mvc

<HttpPost>
Public Async Function UploadWithWatermark(file As IFormFile) As Task(Of IActionResult)
    If file Is Nothing OrElse file.Length = 0 Then
        Return BadRequest("No file selected.")
    End If

    Using stream As New MemoryStream()
        Await file.CopyToAsync(stream)
        Dim originalBytes As Byte() = stream.ToArray()

        ' Load the uploaded file into IronPDF
        Dim pdf = New IronPdf.PdfDocument(originalBytes)

        ' Apply an HTML watermark centered on every page
        pdf.ApplyWatermark(
            "<h2 style='color:red;opacity:0.4'>CONFIDENTIAL</h2>",
            rotation:=45,
            opacity:=60,
            verticalAlignment:=IronPdf.Editing.VerticalAlignment.Middle,
            horizontalAlignment:=IronPdf.Editing.HorizontalAlignment.Center
        )

        Dim pdfFile As New PdfFileModel With {
            .FileName = Path.GetFileName(file.FileName),
            .ContentType = "application/pdf",
            .FileData = pdf.BinaryData,
            .UploadedDate = DateTime.UtcNow
        }

        _context.PdfFiles.Add(pdfFile)
        Await _context.SaveChangesAsync()

        Return RedirectToAction(NameOf(Index))
    End Using
End Function
$vbLabelText   $csharpLabel

水印配置选项

IronPDF 的 ApplyWatermark 方法接受一个 HTML 字符串,这意味着您的水印可以包含任何有效的 HTML 和内联 CSS——渐变、自定义字体、旋转文本,甚至是嵌入的 SVG 图标。 rotation 参数可使水印沿页面对角线旋转,而 opacity 可控制透明度,范围从 0(不可见)到 100(完全不透明)。

除了水印之外,同一个 PdfDocument 对象还公开了添加页眉和页脚给图像加盖水印以及编辑现有表单字段的方法。 在调用 pdf.BinaryData 获取最终字节数组之前,您可以链接多个处理步骤。

如何在 ASP.NET C# 中使用 IronPDF 上传和下载 PDF 文件:图 2 - 带有水印的 PDF 文件保存到数据库

如何下载数据库中存储的PDF文件?

要将存储的 PDF 提供回浏览器,请按 ID 检索记录并返回 FileResult。 ASP.NET Core 辅助方法设置正确的标头,并使用原始文件名触发浏览器的下载对话框。

public async Task<IActionResult> Download(int id)
{
    var pdfFile = await _context.PdfFiles.FindAsync(id);

    if (pdfFile is null)
        return NotFound();

    return File(pdfFile.FileData, pdfFile.ContentType, pdfFile.FileName);
}
public async Task<IActionResult> Download(int id)
{
    var pdfFile = await _context.PdfFiles.FindAsync(id);

    if (pdfFile is null)
        return NotFound();

    return File(pdfFile.FileData, pdfFile.ContentType, pdfFile.FileName);
}
Imports System.Threading.Tasks
Imports Microsoft.AspNetCore.Mvc

Public Async Function Download(id As Integer) As Task(Of IActionResult)
    Dim pdfFile = Await _context.PdfFiles.FindAsync(id)

    If pdfFile Is Nothing Then
        Return NotFound()
    End If

    Return File(pdfFile.FileData, pdfFile.ContentType, pdfFile.FileName)
End Function
$vbLabelText   $csharpLabel

在视图中显示下载列表

Index 操作检索所有已存储的文件记录,并将它们传递给 Razor 视图。 一个简单的 HTML 表格会显示每条记录的文件名、上传日期和下载链接。

<table class="content__data-table" data-content-table>
    <caption>Uploaded PDF Files</caption>
    <thead>
        <tr>
            <th>File Name</th>
            <th>Uploaded</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.FileName</td>
                <td>@item.UploadedDate.ToString("yyyy-MM-dd HH:mm")</td>
                <td><a href="/Pdf/Download/@item.Id">Download</a></td>
            </tr>
        }
    </tbody>
</table>
<table class="content__data-table" data-content-table>
    <caption>Uploaded PDF Files</caption>
    <thead>
        <tr>
            <th>File Name</th>
            <th>Uploaded</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.FileName</td>
                <td>@item.UploadedDate.ToString("yyyy-MM-dd HH:mm")</td>
                <td><a href="/Pdf/Download/@item.Id">Download</a></td>
            </tr>
        }
    </tbody>
</table>
$vbLabelText   $csharpLabel

return File(bytes, contentType, fileName) 重载同时设置 Content-Type: application/pdfContent-Disposition: attachment; 文件名=&quot;...&quot; 标头。 如果您希望浏览器直接打开 PDF 文件而不是提示下载,请使用 return File(bytes, contentType) 而不带第三个参数 -- 这样就省略了 Content-Disposition: attachment 指令。

 如何使用 IronPDF 在 ASP .NET C# 中上传和下载 PDF 文件:图像 3 - 存储的 PDF 文件列表

文件系统存储作为一种替代方案

对于大型部署,在数据库中存储原始二进制数据会增加行大小,并可能降低查询速度。 另一种方法是将文件写入磁盘上的目录(或云提供商),而只在数据库中存储相对路径。 将 FileData byte[] 替换为 FilePath string,在上传时写入 System.IO.File.WriteAllBytesAsync(path, bytes),在下载时读取 System.IO.File.ReadAllBytesAsync(path)。 两条路径都汇聚到控制器中的同一个 return File(...) 调用。

如何按需生成 PDF 文档并提供下载?

您不仅限于提供预先存储的文件。 IronPDF 的 HTML 转 PDF 功能允许您在请求时根据数据动态生成文档——适用于发票、报告、证书和数据导出。

public IActionResult GenerateInvoice(int orderId)
{
    // Build HTML content from your data model
    string html = $@"
        <html>
        <body style='font-family: Arial, sans-serif; padding: 40px;'>
            <h1>Invoice #{orderId}</h1>
            <p>Generated: {DateTime.UtcNow:yyyy-MM-dd HH:mm} UTC</p>
            <table border='1' cellpadding='8'>
                <tr><th>Item</th><th>Qty</th><th>Price</th></tr>
                <tr><td>IronPDF License</td><td>1</td><td>$749</td></tr>
            </table>
        </body>
        </html>";

    var renderer = new IronPdf.ChromePdfRenderer();
    using var pdf = renderer.RenderHtmlAsPdf(html);

    return File(pdf.BinaryData, "application/pdf", $"invoice-{orderId}.pdf");
}
public IActionResult GenerateInvoice(int orderId)
{
    // Build HTML content from your data model
    string html = $@"
        <html>
        <body style='font-family: Arial, sans-serif; padding: 40px;'>
            <h1>Invoice #{orderId}</h1>
            <p>Generated: {DateTime.UtcNow:yyyy-MM-dd HH:mm} UTC</p>
            <table border='1' cellpadding='8'>
                <tr><th>Item</th><th>Qty</th><th>Price</th></tr>
                <tr><td>IronPDF License</td><td>1</td><td>$749</td></tr>
            </table>
        </body>
        </html>";

    var renderer = new IronPdf.ChromePdfRenderer();
    using var pdf = renderer.RenderHtmlAsPdf(html);

    return File(pdf.BinaryData, "application/pdf", $"invoice-{orderId}.pdf");
}
Imports System
Imports Microsoft.AspNetCore.Mvc
Imports IronPdf

Public Class InvoiceController
    Inherits Controller

    Public Function GenerateInvoice(orderId As Integer) As IActionResult
        ' Build HTML content from your data model
        Dim html As String = $"
            <html>
            <body style='font-family: Arial, sans-serif; padding: 40px;'>
                <h1>Invoice #{orderId}</h1>
                <p>Generated: {DateTime.UtcNow:yyyy-MM-dd HH:mm} UTC</p>
                <table border='1' cellpadding='8'>
                    <tr><th>Item</th><th>Qty</th><th>Price</th></tr>
                    <tr><td>IronPDF License</td><td>1</td><td>$749</td></tr>
                </table>
            </body>
            </html>"

        Dim renderer As New ChromePdfRenderer()
        Using pdf = renderer.RenderHtmlAsPdf(html)
            Return File(pdf.BinaryData, "application/pdf", $"invoice-{orderId}.pdf")
        End Using
    End Function
End Class
$vbLabelText   $csharpLabel

按需 PDF 的渲染选项

ChromePdfRenderer 使用与 Google Chrome 相同的 Chromium 渲染引擎生成像素级精确输出。 这意味着任何可以在浏览器中显示的 CSS(flexbox 布局、网格、自定义字体、SVG 图表)都可以在生成的 PDF 中正确呈现。 您可以通过 RenderingOptions 属性在调用 RenderHtmlAsPdf 之前设置纸张大小、边距和方向。

对于更复杂的文档,请将完整的 URL 传递给 RenderUrlAsPdf,而不是 HTML 字符串。 IronPDF 将在无头浏览器中加载页面,执行 JavaScript,应用样式,并将完全渲染的 DOM 转换为 PDF。 查看HTML 转 PDF 转换指南,了解完整的渲染选项,包括自定义页眉、页脚和页码标记。

 如何使用 IronPDF 在 ASP .NET C# 中上传和下载 PDF 文件:图片 4 - 生成 PDF 示例

如何在 ASP.NET Core 中合并多个 PDF 文件?

除了单文件操作之外,您可能还需要将多个上传的文档合并为一个文档。 IronPDF 的PDF 合并功能接受一个 PdfDocument 对象列表,并返回一个合并后的文件。

public async Task<IActionResult> MergeAll()
{
    var allFiles = await _context.PdfFiles.ToListAsync();

    if (allFiles.Count < 2)
        return BadRequest("At least two files are required for merging.");

    var documents = allFiles
        .Select(f => new IronPdf.PdfDocument(f.FileData))
        .ToList();

    using var merged = IronPdf.PdfDocument.Merge(documents);

    return File(merged.BinaryData, "application/pdf", "merged.pdf");
}
public async Task<IActionResult> MergeAll()
{
    var allFiles = await _context.PdfFiles.ToListAsync();

    if (allFiles.Count < 2)
        return BadRequest("At least two files are required for merging.");

    var documents = allFiles
        .Select(f => new IronPdf.PdfDocument(f.FileData))
        .ToList();

    using var merged = IronPdf.PdfDocument.Merge(documents);

    return File(merged.BinaryData, "application/pdf", "merged.pdf");
}
Imports System.Threading.Tasks
Imports Microsoft.AspNetCore.Mvc

Public Async Function MergeAll() As Task(Of IActionResult)
    Dim allFiles = Await _context.PdfFiles.ToListAsync()

    If allFiles.Count < 2 Then
        Return BadRequest("At least two files are required for merging.")
    End If

    Dim documents = allFiles _
        .Select(Function(f) New IronPdf.PdfDocument(f.FileData)) _
        .ToList()

    Using merged = IronPdf.PdfDocument.Merge(documents)
        Return File(merged.BinaryData, "application/pdf", "merged.pdf")
    End Using
End Function
$vbLabelText   $csharpLabel

从 PDF 中拆分页面

反向操作——提取页面子集——使用 CopyPages。 从存储的字节中加载 PdfDocument,使用从零开始的页索引调用 source.CopyPages(startIndex, endIndex),并将结果 PdfDocument.BinaryData 作为 FileResult 返回。 这种模式适用于分页预览、拆分多节报告或提取封面页以生成缩略图。 您还可以在将合并或拆分后的输出提供给用户之前,对其进行数字签名

如何安全地处理大文件上传?

大型 PDF 文件需要在 ASP.NET Core 中间件级别进行额外配置。 默认情况下,请求体大小限制设置为大约 28 MB。 要提高它,请调用 builder.Services.Configure<FormOptions> 来设置 MultipartBodyLengthLimitbuilder.WebHost.ConfigureKestrel 来设置 Limits.MaxRequestBodySize -- 两者都设置为您所需的字节数,例如 50 * 1024 * 1024 表示 50 MB -- 在 Program.cs 之前,在 builder.Build() 之前。

除了大小限制之外,还应将以下安全措施应用于每个上传端点:验证内容类型标头,检查流的前几个字节是否有 %PDF 魔数,使用 IronPDF 的文档检查 API 扫描嵌入式脚本,并将处理后的文件存储在 Web 根目录之外,这样它们就永远不会直接作为静态内容提供。 ASP.NET Core 安全文档涵盖了其他强化技术,包括防伪令牌验证和病毒扫描集成。

流式传输大文件以避免内存压力

当文件超过 10 MB 时,在处理之前将整个流读取到 MemoryStream 中可能会显著增加内存使用量。 使用 IronPdf.PdfDocument.FromStream 尽可能直接从请求流加载,或者写入临时文件路径并从磁盘加载:

string tempPath = Path.GetTempFileName();
await using (var fs = System.IO.File.Create(tempPath))
{
    await file.CopyToAsync(fs);
}

using var pdf = new IronPdf.PdfDocument(tempPath);
// process...
System.IO.File.Delete(tempPath);
string tempPath = Path.GetTempFileName();
await using (var fs = System.IO.File.Create(tempPath))
{
    await file.CopyToAsync(fs);
}

using var pdf = new IronPdf.PdfDocument(tempPath);
// process...
System.IO.File.Delete(tempPath);
Imports System.IO
Imports IronPdf

Dim tempPath As String = Path.GetTempFileName()

Using fs As FileStream = System.IO.File.Create(tempPath)
    Await file.CopyToAsync(fs)
End Using

Using pdf As PdfDocument = New IronPdf.PdfDocument(tempPath)
    ' process...
End Using

System.IO.File.Delete(tempPath)
$vbLabelText   $csharpLabel

这种模式可以保持较低的堆分配量,并且非常适合后台处理队列,在 HTTP 响应发送后,文件会异步处理。 请查阅IronPDF 文档,了解更多异步处理模式。

下一步计划是什么?

现在,您已经拥有了在由 IronPDF 支持的 ASP.NET Core MVC 应用程序中上传、处理、存储和下载 PDF 文件的完整基础。 接下来,请参考以下方向来扩展工作流程。

扩展处理能力。IronPDF支持填写和读取 PDF 表单字段,使用PDF 文本提取 API提取文本和图像,以及将PDF 页面转换为图像以进行缩略图预览。 这些功能中的每一个都集成到上面所示的同一控制器模式中。

添加数字签名。在存储之前,使用 X.509 证书对生成或上传的每个文档进行数字签名。 签名后的 PDF 文件包含防篡改元数据,满足多项合规性要求。

将存储扩展到云端。将本地数据库列替换为 Azure Blob 存储或 Amazon S3 引用。 将处理后的字节上传到云存储并添加水印,只在数据库中保存 URI——这大大减少了数据库行的大小,并实现了 CDN 交付。

立即开始免费试用。访问IronPDF 试用许可页面,获取可体验全部功能的 30 天评估密钥。 您还可以浏览完整的IronPDF 功能概述,了解 .NET 应用程序中可用的全部 PDF 功能,或者在准备进行生产部署时查阅定价和许可页面

常见问题解答

如何在 ASP.NET Core MVC 应用程序中上传 PDF 文件?

要在 ASP.NET Core MVC 应用程序中上传 PDF 文件,您可以使用 IFormFile 接口从表单中捕获文件数据,然后在保存之前在服务器端进行处理,可能的话还可以借助 IronPDF 进一步处理 PDF。

在 ASP.NET 中下载 PDF 文件的最佳方法是什么?

在 ASP.NET 中下载 PDF 文件的最佳方法是在控制器中使用 FileResult 操作。IronPDF 可协助在服务器端生成和修改 PDF 文件,以确保它们随时可供下载。

能否使用 ASP.NET 在数据库中存储 PDF 文件?

是的,您可以使用 ASP.NET 将 PDF 文件转换为字节数组并保存为二进制大对象 (BLOB),从而将 PDF 文件存储到数据库中。IronPDF 可以帮助在存储前处理 PDF。

IronPDF 如何帮助在 ASP.NET 中添加 PDF 水印?

IronPDF 为 PDF 提供了轻松添加文本或图像水印的功能,可将其集成到您的 ASP.NET 应用程序中,以便在下载或存储前修改文档。

使用 EF Core 存储 PDF 有哪些优势?

EF Core 可实现高效的对象关系映射,使您更容易在 ASP.NET 应用程序中以结构化和可扩展的方式管理 PDF 的存储和检索。

是否可以在 ASP.NET 应用程序中处理 PDF 内容?

是的,使用 IronPDF,您可以操作 PDF 内容,包括编辑文本、图像和元数据,这对于在文档提供给用户之前对其进行定制非常有用。

如何在 ASP.NET 中安全地处理文件上传?

要在 ASP.NET 中安全地处理文件上传,应验证文件类型、限制文件大小并将其存储在安全位置。使用 IronPDF 等库还有助于确保 PDF 文件本身的完整性。

在网络应用程序中使用 PDF 时有哪些常见挑战?

常见的挑战包括确保文件兼容性、管理大文件大小以及保持文档完整性。IronPDF 为 PDF 创建和操作提供了强大的工具,有助于克服这些难题。

我能否在 ASP.NET 中将不同类型的文件转换为 PDF?

是的,IronPDF 允许您在 ASP.NET 应用程序中将 HTML 或图像文件等各种文件类型无缝转换为 PDF。

在 ASP.NET 中处理 PDF 时,模型-视图-控制器 (MVC) 的作用是什么?

MVC 模式通过分离数据处理(模型)、用户界面(视图)和应用逻辑(控制器)来帮助组织处理 PDF 的代码,从而使管理和扩展 PDF 功能变得更加容易。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

钢铁支援团队

我们每周 5 天,每天 24 小时在线。
聊天
电子邮件
打电话给我