萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 將圖片以 Base64 編碼儲存至 XML 的完整實作

核心概念

XML 為純文字格式,無法直接儲存二進位資料。解決方案:將圖片讀取為位元組陣列 → **Base64 編碼** → 寫入 XML 文字節點。.NET 提供 `XmlTextWriter.WriteBase64` 直接支援串流式編碼寫入,避免大圖載入記憶體。

完整儲存範例

public void SaveImageToXml(string imagePath, string xmlPath)
{
    const int BufferSize = 8192; // 8KB 緩衝區
    byte[] buffer = new byte[BufferSize];
    int bytesRead;

    using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
    using (BinaryReader br = new BinaryReader(fs))
    using (XmlTextWriter xw = new XmlTextWriter(xmlPath, Encoding.UTF8))
    {
        xw.Formatting = Formatting.Indented;
        xw.WriteStartDocument();
        xw.WriteStartElement("picture", "ContactDetails", "https://example.com/ns");
        xw.WriteStartElement("image");
        xw.WriteAttributeString("imageName", Path.GetFileName(imagePath));
        xw.WriteAttributeString("contentType", GetMimeType(imagePath));
        xw.WriteAttributeString("length", fs.Length.ToString());

        // 串流式 Base64 編碼寫入
        while ((bytesRead = br.Read(buffer, 0, BufferSize)) > 0)
        {
            xw.WriteBase64(buffer, 0, bytesRead);
        }

        xw.WriteEndElement(); // image
        xw.WriteEndElement(); // picture
        xw.WriteEndDocument();
    }
}

private string GetMimeType(string path)
{
    var ext = Path.GetExtension(path).ToLowerInvariant();
    return ext switch
    {
        ".jpg" or ".jpeg" => "image/jpeg",
        ".png" => "image/png",
        ".gif" => "image/gif",
        ".bmp" => "image/bmp",
        _ => "application/octet-stream"
    };
}

讀取並還原圖片

public void RestoreImageFromXml(string xmlPath, string outputDir)
{
    using (XmlTextReader xr = new XmlTextReader(xmlPath))
    {
        xr.MoveToContent();
        string fileName = xr.GetAttribute("imageName");
        string contentType = xr.GetAttribute("contentType");
        long length = long.Parse(xr.GetAttribute("length"));

        xr.ReadStartElement("image"); // 定位到 Base64 內容

        string outputPath = Path.Combine(outputDir, fileName);
        using (FileStream fs = new FileStream(outputPath, FileMode.Create))
        {
            byte[] buffer = new byte[8192];
            int decoded;
            // XmlTextReader 內建 Base64 解碼
            while ((decoded = xr.ReadContentAsBase64(buffer, 0, buffer.Length)) > 0)
            {
                fs.Write(buffer, 0, decoded);
            }
        }
    }
}

關鍵技術點

  1. WriteBase64 / ReadContentAsBase64:.NET 內建串流編解碼,**不需手動 `Convert.ToBase64String`**,節省記憶體,支援任意大小檔案。
  2. 緩衝區大小:4KB~64KB 為宜,平衡呼叫次數與記憶體佔用。
  3. 中繼資料:建議在 XML 記錄檔名、MIME 類型、原始長度,利於還原與驗證。
  4. 命名空間:範例示範 `WriteStartElement(localName, ns)` 正確產生帶命名空間的 XML。

替代方案比較

| 方案 | 優點 | 缺點 | |------|------|------| | **Base64 嵌入 XML** | 單一檔案、純文字、跨平台傳輸 | 體積膨脹 ~33%、XML 解析較慢 | | **Base64 存資料庫** | 交易一致性、備份簡單 | DB 膨脹、不利索引、備份龐大 | | **檔案系統 + XML 存路徑** | 體積小、效能好、可 CDN | 需管理檔案權限、部署較複雜 | | **GridFS / Blob Storage** | 專為大二進位設計、支援分塊 | 架構較重、需額外基礎建設 |

適用場景建議

  • 小型設定檔、離線資料包、行動裝置同步封裝 → **Base64 in XML 合適**
  • 大量圖片、頻繁存取、Web 直接顯示 → **檔案系統/Blob Storage + URL 參考**
  • 需資料庫交易一致性 → **資料庫 VARBINARY/Blob + 交易控制**

掌握 `XmlTextWriter.WriteBase64` 串流式編碼技巧,即可優雅處理「XML 承載二進位資料」的需求,兼顧記憶體效率與程式碼簡潔性。

copyright © 萬盛學電腦網 all rights reserved