Asp.net

將 MemoryStream 文件儲存到 Azure Blob

  • December 14, 2021

我有一個通過 System.Drawing 動態生成的圖像。然後我將生成的圖像輸出到一個MemoryStream用於儲存到我的 Azure blob 中。

但我似乎無法將我的文件儲存在我選擇的 blob 中。沒有發生錯誤,我的圖像已成功保存到MemoryStream. 正如預期的那樣,我的 blob 是空的。

我已確保我的 blob 容器具有公共讀/寫訪問權限。

程式碼

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue("CMSAzureAccountName").ToString(), Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue("CMSAzureSharedKey").ToString()));

// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("myimagecontainer");

// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("test.jpg");
           
//Output image
ImageCodecInfo[] Info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
EncoderParameters Params = new System.Drawing.Imaging.EncoderParameters(1);
Params.Param[0] = new EncoderParameter(Encoder.Quality, 100L);

System.IO.MemoryStream msImage = new System.IO.MemoryStream();
GenerateImage.Render(imageOutput).Save(msImage, Info[1], Params); //GenerateImage.Render() method creates a custom image and returns a Bitmap
           
// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = msImage)
{
   blockBlob.UploadFromStream(fileStream);
}

任何幫助,將不勝感激。

更新

我設法找到了錯誤的主要原因。我需要更改以下內容:

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue("CMSAzureAccountName").ToString(), Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue("CMSAzureSharedKey").ToString()));

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DiagnosticsConnectionString"));

但我會將“Gaurav Mantri”回复標記為正確。如果不是他的洞察力,我的圖像不會上傳到 blob。

嘗試將記憶體流的位置設置為 0,看看是否有幫助。類似於下面的程式碼:

msImage.Position = 0;//Move the pointer to the start of stream.

// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = msImage)
{
   blockBlob.UploadFromStream(fileStream);
}

我有同樣的問題,程式碼有效,但 pdf 文件大小始終為 0,我必須使 MyMemoryStream.Position = 0; 下面是我使用的程式碼。希望它可以幫助某人。

using (pdfStream)
{
   pdfStream.Position = 0;
   blob.UploadFromStream(pdfStream);                            
   _model.ConvertedPdfUrl = blob.Uri.AbsoluteUri;
}

引用自:https://stackoverflow.com/questions/14999682