【问题标题】:Errors converting form file to memory stream将表单文件转换为内存流时出错
【发布时间】:2016-07-11 23:58:49
【问题描述】:

我正在尝试上传文件并保存到 Azure Blob 存储中。 该文件作为 FormFile 注入。 问题是,当我将 FormFile 转换为内存流时出现错误。流然后上传到 Azure,但不包含任何数据。

 public async Task<IActionResult> Create([Bind("EndorsementId,FileName,ProviderId,Title")] Endorsement endorsement, IFormFile formFile)
    {
        if (ModelState.IsValid)
        {
            ...
            var data = new MemoryStream();

            formFile.CopyTo(data);
            var buf = new byte[data.Length];
            data.Read(buf, 0, buf.Length);

            UploadToAzure(data);

            ...

错误出现在内存流的 ReadTimeOut 和 WriteTimeOut 属性上。他们说“data.ReadTimeout”引发了“System.InvalidOperationException”类型的异常,“data.WriteTimeout”分别引发了“System.InvalidOperationException”类型的异常。

这是我注入 FormFile 的方式。这方面的信息似乎很少。 http://www.mikesdotnetting.com/article/288/uploading-files-with-asp-net-core-1-0-mvc

提前致谢。

【问题讨论】:

  • 旁注:忽略对流的读/写操作的结果通常是个坏主意。

标签: c# asp.net asp.net-mvc asp.net-core-mvc asp.net-core-1.0


【解决方案1】:

IFormFile 具有用于此目的的 CopyToAsync 方法。您可以执行以下操作:

using (var outputStream = await blobReference.OpenWriteAsync())
{
    await formFile.CopyToAsync(outputStream, cancellationToken);
}

【讨论】:

    【解决方案2】:

    填完数据后MemoryStream的偏移量还在文件末尾。您可以重置位置:

    var data = new MemoryStream();
    
    formFile.CopyTo(data);
    // At this point, the Offset is at the end of the MemoryStream
    // Either do this to seek to the beginning
    data.Seek(0, SeekOrigin.Begin);
    
    var buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);
    
    UploadToAzure(data);
    

    或者,您可以让MemoryStream 将数据复制到byte[] 数组中,而不是自己完成所有工作,方法是在CopyTo() 调用之后执行此操作:

    // Or, save yourself some work and just do this 
    // to make MemoryStream do the work for you
    UploadToAzure(data.ToArray());
    

    【讨论】:

      【解决方案3】:

      您也可以像这样将 IFormFile 的内容上传到 Azure Blob 存储:

      using (var stream = formFile.OpenReadStream())
      {
          var blobServiceClient = new BlobServiceClient(azureBlobConnectionString);
          var containerClient = blobServiceClient.GetBlobContainerClient("containerName");
          var blobClient = containerClient.GetBlobClient("filename");
      
          await blobClient.UploadAsync(stream);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-03
        • 1970-01-01
        • 2011-07-17
        • 1970-01-01
        • 2014-08-12
        • 2020-12-25
        • 2013-02-02
        • 2012-11-13
        相关资源
        最近更新 更多