簡體   English   中英

如何使用 c# 從 MongoDB 數據庫中檢索 pdf

[英]How to retrieve a pdf from MongoDB database using c#

我將 pdf 個文件保存到 MongoDB。我試圖將所有文件轉換為 base64,但我無法從數據庫中檢索實際文件。 文件路徑不是我所期望的,我不確定還可以嘗試什么

下面是我試過的代碼。 錯誤信息是:

"System.IO.IOException Message=The filename, directory name, or volume label syntax is incorrect. : 'C:\Users\Jabari.LAPTOP-FERO3UB5\Desktop\codebase\LMO\API\LMO.Api\https:\LMOdevstorage.blob.core.windows.net\documents\57a36b7e6789102ddf\J_Broomstick58059342787ba42f12345.pdf'

據我所知,它試圖從我的本地代碼庫中提取數據,而不是實際的數據庫。 我不確定這是為什么。 我是 MongoDB 操作的新手。

下面是我的代碼

var file = document.AzureDocumentUri;
if (file != null)
{
    Byte[] bytes = File.ReadAllBytes(file);
    String base64String = Convert.ToBase64String(bytes);
    StreamWriter sw64 = new StreamWriter($"{filePath}test64.txt");
    sw64.Write(base64String);
    sw64.Close();
    sw64.Dispose();
}

我期望發生的事情是能夠直接從數據庫訪問 pdf 文件並將其讀入 memory,然后將其轉換為 base64。

為什么它試圖從我的本地目錄而不是從數據庫下載集合?

Byte[] bytes = File.ReadAllBytes(file);

奇怪,你不能這樣下載URI。

要在 MongoDB 中找到使用文件的最佳方式,請查看 GridFS。

MemoryStream ms = new MemoryStream(new byte[] { 0x00, 0x01, 0x02 }); Position 女士 = 0; // MemoryStream ms2 = new MemoryStream(await File.ReadAllBytesAsync("test.pdf"));

// Write to MongoDB
// There is a limitation of 16 MB in record size for mongodb, this what GridFS handle, unlimited file size.
// https://www.mongodb.com/docs/manual/core/document/#:~:text=Document%20Size%20Limit,MongoDB%20provides%20the%20GridFS%20API.
GridFSBucket gridFSBucket = new GridFSBucket(db);
ObjectId id = await gridFSBucket.UploadFromStreamAsync("exemple.bin", ms);

// Get the file
MemoryStream ms3 = new MemoryStream();
await gridFSBucket.DownloadToStreamAsync(id, ms3);

完整示例在這里

https://github.com/iso8859/learn-mongodb-by-example/blob/main/do.net/02%20-%20Intermediate/StoreFile.cs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM