【问题标题】:adding to azure blob storage with stream使用流添加到 azure blob 存储
【发布时间】:2017-11-14 22:06:49
【问题描述】:

我正在尝试将通过 .net 核心 Web API 接收的 IFormFile 添加到 azure blob 存储。这些是我设置的属性:

static internal CloudStorageAccount StorageAccount => 
    new CloudStorageAccount(new StorageCredentials(AccountName, AccessKey, AccessKeyName), true);

// Create a blob client.
static internal CloudBlobClient BlobClient => StorageAccount.CreateCloudBlobClient();

// Get a reference to a container 
static internal CloudBlobContainer Container(string ContainerName) 
                        => BlobClient.GetContainerReference(ContainerName);

static internal CloudBlobContainer ProfilePicContainer 
        => Container(ProfilePicContainerName);

现在我像这样使用ProfilePicContainer

var Container = BlobStorage.ProfilePicContainer;
string fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(ProfileImage.FileName);
var blockBlob = Container.GetBlockBlobReference(fileName);
var fileStream = ProfileImage.OpenReadStream();
fileStream.Position = 0;
await blockBlob.UploadFromStreamAsync(fileStream);

这给了我以下错误:

Microsoft.WindowsAzure.Storage.StorageException: '无法访问已关闭的流。'

内部异常 ObjectDisposedException:无法访问已关闭的 Stream。

在调试时,我甚至在fileStream.Position = 0 之前就注意到它的位置已经是 0。但是我添加了该行,因为我收到了这个错误。同样在 await 行,fileStream_disposed 设置为 false。

此外,关于 blob 连接,我尝试为字符串常量 AccessKey 设置无效值,它显示完全相同的错误。这意味着我不知道它是否甚至是连接。我已经在调试器中检查了blobBlock 中的所有值,但我不知道如何验证它是否已连接。

【问题讨论】:

  • 听起来fileStream 已经关闭而不是azure storage sdk 的问题?您可以访问fileStream 流吗?你能用using (var testStream = File.OpenWrite(Path.GetTempFileName())) fileStream.CopyTo(testStream)之类的东西把它写到磁盘吗?
  • 是的,已经尝试使用 fileStream 写入文件和写入字节。两者都工作正常。
  • 尝试将流放在 using 块中
  • 我之前尝试过。我有其他错误,并在网上看到建议不要使用 using

标签: c# asynchronous azure-storage filestream asp.net-core-webapi


【解决方案1】:

尝试直接从流中写入时似乎存在一些问题。我能够通过将流转换为字节数组来运行代码。

await blockBlob.UploadFromByteArrayAsync(ReadFully(fileStream, blockBlob.StreamWriteSizeInBytes),
                            0, (int)fileStream.Length);

ReadFully 是对此答案 https://stackoverflow.com/a/221941 的修改

static byte[] ReadFully(Stream input, int size)
{
    byte[] buffer = new byte[size];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, size)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

【讨论】:

  • 多个文件 50 MB 到 300 MB 会不会有比较性能问题?
  • 我还没有测试过。但您始终可以使用模拟的离线 blob 存储并对其进行测试
猜你喜欢
  • 2019-05-26
  • 2020-06-17
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 2023-04-08
  • 1970-01-01
  • 2017-09-21
  • 2017-04-18
相关资源
最近更新 更多