[英]Azure blob storage download to stream returning “” asp.net
我目前正在嘗試使用DownloadToStream方法從Azure blob存儲中下載文件,以將blob的內容下載為文本字符串。 但是我沒有得到任何回報,只是一個空字符串。
這是我用來連接azure blob容器並檢索blob文件的代碼。
public static string DownLoadFroalaImageAsString(string blobStorageName, string companyID)
{
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(companyID.ToLower());
//retrieving the actual filename of the blob
string removeString = "BLOB/";
string trimmedString = blobStorageName.Remove(blobStorageName.IndexOf(removeString), removeString.Length);
// Retrieve reference to a blob named "trimmedString"
CloudBlockBlob blockBlob2 = container.GetBlockBlobReference(trimmedString);
string text;
using (var memoryStream = new MemoryStream())
{
blockBlob2.DownloadToStream(memoryStream);
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
return text;
}
我正在關注這個文檔但是我似乎無法讓它工作。 任何幫助將不勝感激。
但是我沒有得到任何回報,只是一個空字符串。
我測試你提供的代碼在我身邊,它正常工作。 我假設您的情況下測試blob內容為空 。 我們可以通過以下方式解決問題:
1.請嘗試檢查memoryStream的長度。 如果長度等於0,我們可以知道blob內容為空。
using (var memoryStream = new MemoryStream())
{
blockBlob2.DownloadToStream(memoryStream);
var length = memoryStream.Length;
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
2.我們可以將包含內容的blob上傳到容器,我們可以輕松地使用Azure門戶或Microsoft Azure存儲資源管理器 。 請嘗試使用上傳的blob進行測試。
如果要從blob獲取文本,可以使用DownloadTextAsync()
var text = await blockBlob2.DownloadTextAsync();
如果要將文件流返回到API respoinse,可以使用FileStreamResult,即IActionResult。
var stream = await blockBlob2.OpenReadAsync();
return File(stream, blockBlob2.Properties.ContentType, "name");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.