當前位置: 妍妍網 > 碼農

ASP.NET Core介面:上傳並讀取DOCX文件內容

2024-06-01碼農

在ASP.NET Core中,處理檔上傳並讀取檔內容是一個常見的需求。特別是當需要處理Microsoft Word文件(如DOCX)時,這一功能變得尤為重要。本文將指導您如何在ASP.NET Core介面中實作DOCX文件的上傳和內容的讀取。

第一步:建立ASP.NET Core計畫

首先,確保您已經安裝了.NET Core SDK。然後,使用以下命令建立一個新的ASP.NET Core Web API計畫:

dotnet new webapi -n DocxUploadAndRead
cd DocxUploadAndRead

第二步:添加必要的NuGet包

為了讀取DOCX檔的內容,我們將使用 DocumentFormat.OpenXml 包。這個包提供了對Open XML格式的讀寫能力,是處理Office文件的一種有效方式。

透過NuGet安裝 DocumentFormat.OpenXml 包:

dotnet add package DocumentFormat.OpenXml

第三步:建立檔上傳的API端點

Controllers 資料夾中,建立一個新的API控制器,例如 DocxController 。然後,添加一個用於處理檔上傳的POST方法。

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
[ApiController]
[Route("[controller]")]
public classDocxController : ControllerBase
{
[HttpPost("upload")]
publicasync Task<IActionResult> UploadDocx(IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest("No file uploaded.");
if (file.ContentType != "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
return BadRequest("Invalid file type.");
using (var stream = new MemoryStream())
{
await file.CopyToAsync(stream);
stream.Position = 0;
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, false))
{
Body body = wordDocument.MainDocumentPart.Document.Body;
foreach (var para in body.Elements<Paragraph>())
{
foreach (var run in para.Elements<Run>())
{
foreach (var text in run.Elements<Text>())
{
// 在這裏處理文本內容,例如打印到控制台或儲存到資料庫等。
System.Console.WriteLine(text.Text);
}
}
}
}
}
return Ok("File uploaded and processed successfully.");
}
}



在上面的程式碼中,我們建立了一個名為 UploadDocx 的POST方法,該方法接受一個 IFormFile 型別的參數,用於接收上傳的檔。我們檢查檔是否為空以及檔的MIME型別是否為DOCX。然後,我們將檔內容復制到一個記憶體流中,並使用 DocumentFormat.OpenXml 庫開啟並處理DOCX檔的內容。在這個例子中,我們只是簡單地將檔中的文本內容打印到控制台。

第四步:測試API

現在,您可以執行計畫並使用Postman、Curl或任何其他HTTP客戶端向 /docx/upload 端點發送包含DOCX檔的POST請求。確保在請求體中設定正確的 Content-Type multipart/form-data )並將檔作為表單數據的一部份上傳。

# 使用Curl的例子命令(請根據您的實際情況替換檔路徑)
curl -X POST http://localhost:5000/docx/upload -F "file=@/path/to/your/document.docx"

如果一切正常,您應該會在控制台中看到DOCX檔中的所有文本內容,並且客戶端會收到一個表示成功的響應。

結論

在本文中,我們介紹了如何在ASP.NET Core Web API中建立一個介面,用於上傳DOCX檔並讀取其內容。透過使用 DocumentFormat.OpenXml 庫,我們可以輕松地處理Open XML格式的Word文件。這種方法為處理復雜文件格式提供了一種強大而靈活的方式,使得在伺服器端進行文件內容分析和處理成為可能。