如何在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
安裝完成後,IronPDF 提供以下功能:ChromePdfRenderer 用於從 HTML 產生 PDF,PdfDocument 用於載入和操作現有文件,以及一系列編輯工具,包括浮水印、圖章和數位簽章。 您可以查看完整的IronPDF NuGet 套件頁面,以了解版本歷史記錄和相容性說明。
設定專案
在 Program.cs 新增儲存路徑常數,並將您的 ApplicationDbContext 註冊到依賴注入容器。 在編寫任何 PDF 特定邏輯之前,您的專案結構將包含 Controllers/PdfController.cs、Models/PdfFileModel.cs 和 Data/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
FileData 將 PDF 儲存為二進位大物件 (BLOB)。 這種方法將文件保留在資料庫中,使備份更簡單,查詢更直接。 對於高容量場景或大型文件,可以考慮僅在資料庫中儲存文件路徑,並將二進位檔案寫入雲端儲存桶,例如Azure Blob Storage或Amazon S3 。
設定 Entity Framework Core
透過向 EF Core 新增 DbSet<PdfFileModel> 屬性來註冊模型 ApplicationDbContext:
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
運行 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
驗證上傳的文件
處理內容前請務必驗證內容類型。 檢查 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。
如何在 ASP.NET C# 中使用 IronPDF 上傳和下載 PDF 檔案:圖 1 - 顯示已上傳 PDF 的 UI
如何在儲存前為上傳的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
浮水印配置選項
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 的 File 輔助方法設定正確的 Content-Type 標頭,並使用原始檔案名稱觸發瀏覽器的下載對話方塊。
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
在視圖中顯示下載列表
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>
return File(bytes, contentType, fileName) 重載同時設定 Content-Type: application/pdf 和 Content-Disposition: attachment; 檔案名稱="..." 標頭。 如果您希望瀏覽器直接開啟 PDF 而不是提示下載,請使用 return File(bytes, contentType) 而不帶第三個參數 -- 這樣就省略了 Content-Disposition: attachment 指令。
文件系統儲存作為一種替代方案
對於大型部署,在資料庫中儲存原始二進位資料會增加行大小,並可能降低查詢速度。 另一種方法是將檔案寫入磁碟上的目錄(或雲端提供者),而只在資料庫中儲存相對路徑。 將 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
按需 PDF 的渲染選項
ChromePdfRenderer 使用與 Google Chrome 相同的 Chromium 渲染引擎產生像素級精確輸出。 這意味著任何可以在瀏覽器中顯示的 CSS(flexbox 版面配置、網格、自訂字體、SVG 圖表)都可以在產生的 PDF 中正確呈現。 您可以透過 RenderingOptions 屬性在呼叫 RenderHtmlAsPdf 之前設定紙張大小、邊距和方向。
對於更複雜的文檔,請將完整的 URL 傳遞給 RenderUrlAsPdf,而不是 HTML 字串。 IronPDF 將在無頭瀏覽器中載入頁面,執行 JavaScript,套用樣式,並將完全渲染的 DOM 轉換為 PDF。 請查看HTML 轉 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
從 PDF 拆分頁面
反向操作——提取頁面子集——使用 CopyPages。 從儲存的位元組載入 PdfDocument,使用從零開始的頁索引呼叫 source.CopyPages(startIndex, endIndex),並將結果 PdfDocument.BinaryData 作為 FileResult 傳回。 這種模式適用於分頁預覽、拆分多節報告或提取封面頁以產生縮圖。 您也可以在將合併或分割後的輸出提供給使用者之前,對其進行數位簽章。
如何安全地處理大文件上傳?
大型 PDF 檔案需要在 ASP.NET Core 中間件層級進行額外配置。 預設情況下,請求體大小限制設定為大約 28 MB。 要提高它,請呼叫 builder.Services.Configure<FormOptions> 來設定 MultipartBodyLengthLimit 和 builder.WebHost.ConfigureKestrel 來設定 Limits.MaxRequestBodySize -- 且兩者都設定為您所需的位元組數,例如 @@--CODE-27136--@@(表示 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)
這種模式可以保持較低的堆分配量,並且非常適合後台處理佇列,在 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,以確保 PDF 可供下載。
我可以使用 ASP.NET 在資料庫中儲存 PDF 檔案嗎?
是的,您可以使用 ASP.NET 將 PDF 檔案轉換為位元組陣列,並將其儲存為二進位大型物件 (BLOB),藉此將 PDF 檔案儲存於資料庫中。IronPDF 可以在存儲之前幫助處理 PDF。
IronPDF 如何在 ASP.NET 中幫助 PDF 進行水印處理?
IronPDF for .NET 提供的功能可以輕鬆地在 PDF 上加入文字或圖片水印,這些水印可以整合到您的 ASP.NET 應用程式中,以便在下載或儲存之前修改文件。
使用 EF Core 儲存 PDF 有哪些優點?
EF Core 允許有效率的物件關聯映射,讓您更容易在 ASP.NET 應用程式中以結構化、可擴充的方式管理 PDF 儲存與檢索。
是否可以在 ASP.NET 應用程式中處理 PDF 內容?
是的,使用 IronPDF,您可以操作 PDF 內容,包括編輯文字、圖片和元資料,這對於在提供給使用者之前自訂文件非常有用。
如何在 ASP.NET 中安全地處理檔案上傳?
若要在 ASP.NET 中安全地處理檔案上傳,您應該驗證檔案類型、限制檔案大小,並將檔案儲存在安全的位置。使用 IronPDF 之類的函式庫也有助於確保 PDF 檔案本身的完整性。
在 Web 應用程式中使用 PDF 時,有哪些常見的挑戰?
常見的挑戰包括確保檔案相容性、管理大檔案大小以及維持文件完整性。IronPDF 提供強大的 PDF 創建和處理工具,有助於克服這些難題。
我可以在 ASP.NET 中將不同類型的檔案轉換為 PDF 嗎?
是的,IronPDF 可讓您在 ASP.NET 應用程式中,將 HTML 或圖片檔案等各種檔案類型無縫轉換為 PDF。
Model-View-Controller (MVC) 在 ASP.NET 中處理 PDF 的角色是什麼?
MVC 模式透過分隔資料處理 (模型)、使用者介面 (視圖) 和應用程式邏輯 (控制器) 來協助組織處理 PDF 的程式碼,使 PDF 功能的管理和擴充更加容易。



