gpt4 book ai didi

c# - 如何将图像从 Asp.net Core IFormFile 上传到 Azure Blob 存储?

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:18 24 4
gpt4 key购买 nike

我正在尝试将图像上传到 azure blob 存储。然而,当我在 azure 上查看最终结果时,它只是创建了一个空文件。

   [HttpPost("Import")]
public IActionResult Import(IFormFile filepond)
{
const string accountName = "accountName";
const string key = "key14881851";

var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("mycontainer");
container.CreateIfNotExistsAsync();
container.SetPermissionsAsync(new BlobContainerPermissions()
{
PublicAccess = BlobContainerPublicAccessType.Blob
});

var blob = container.GetAppendBlobReference("test.jpg");
blob.UploadFromStreamAsync(filepond.OpenReadStream());

return Ok();
}

一些问题(除了为什么我得到一个空文件之外)。

  1. 我看到很多这些方法都是异步的,我是否需要等待它们才能正常工作(即,如果容器不存在,则在将文件写入容器之前创建它)
  2. 我需要将 UploadFromStreamAsync 包装在 using 语句中吗?

最佳答案

...do I need to await them for everything to work properly(ie if the container does not exist that it gets created before a file is written to the container)

是的。异步方法返回一个任务,您必须等待该任务完成。这就是为什么你的文件是空的。

Do I need to wrap the UploadFromStreamAsync in a using statement.

我认为它更干净,但我不确定这里是否绝对有必要。

我会这样写(未经测试):

        var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("mycontainer");
await container.CreateIfNotExistsAsync();
container.SetPermissionsAsync(new BlobContainerPermissions()
{
PublicAccess = BlobContainerPublicAccessType.Blob
});

var blob = container.GetBlockBlobReference("test.jpg");
using(var stream = filepond.OpenReadStream()) {
await blob.UploadFromStreamAsync(stream);
}

请注意,我用 GetBlockBlobReference() 替换了 GetAppendBlobReference()。

带有示例的文档 https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet?tabs=windows

关于c# - 如何将图像从 Asp.net Core IFormFile 上传到 Azure Blob 存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52561285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com