【问题标题】:MemoryStream throws exception of type InvalidOperationExceptionMemoryStream 抛出 InvalidOperationException 类型的异常
【发布时间】:2019-07-17 17:59:27
【问题描述】:

希望能帮到你:)

在我的MVC.net core 2.2中,调试的时候很简单:

MemoryStream ms = new MemoryStream();

在初始化之后它给了我一个:

ReadTimeout: 'ms.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
WriteTimeout: 'ms.WriteTimeout' threw an exception of type 'System.InvalidOperationException'

现在解决方案不会崩溃或发生任何事情。但是,如果我在 Visual Studio 中检查“ms”,那就是它所说的。

我想做的是通过 SixLabors.ImageSharp 做:

IFormFile file = viewModel.File.Image;

using (Image<Rgba32> image = Image.Load(file.OpenReadStream()))
using (var ms = new MemoryStream())
{
    image.Mutate(x => x.Resize(1000, 1000));
    SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder jpegEncoder = 
        new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder();
    jpegEncoder.Quality = 80;

    image.Save(ms, jpegEncoder);

    StorageCredentials storageCredentials = new StorageCredentials("Name", "KeyValue");

    // Create cloudstorage account by passing the storagecredentials
    CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

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

    // Get reference to the blob container by passing the name by reading the value from the configuration (appsettings.json)
    CloudBlobContainer container = blobClient.GetContainerReference("storagefolder");

    // Get the reference to the block blob from the container
    CloudBlockBlob blockBlob = container.GetBlockBlobReference("image.jpg");

    await blockBlob.UploadFromStreamAsync(ms);
}

但是保存的流是空的(调试时Capacity、Length和Position都有值,但是上传到azure blob storage后,大小为0)。

亲切的问候 安达·亨德里克森

【问题讨论】:

  • 请提供更完整的代码示例。您在哪里将流上传到 Azure?
  • 嗨 @Amy 我已经添加了用于将流上传到 Azure 的代码
  • 请尝试两件事:(1)在上传之前尝试刷新内存流;它可能有未写入的字节在缓冲区中等待,并且(2)在上传之前将内存流位置设置为第一个字节。
  • 可以不使用“using”和不使用as var的情况下尝试使用内存流
  • 你太棒了@Amy!有效。感谢您的快速帮助。如果您将其发布为答案,我会标记它:)

标签: c# asp.net-mvc memorystream imagesharp


【解决方案1】:

对内存流的写操作不是原子的,它们被缓冲以提高效率。您需要先刷新流。

第二个问题是,您开始将内存流复制到输出流,从流的末尾开始。因此,将内存流重新定位到开头。

所以,在将流写入输出之前:

ms.Flush();
ms.Position = 0; // or ms.Seek(0, SeekOrigin.Begin);

然后调用

await blockBlob.UploadFromStreamAsync(ms);

【讨论】:

    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多