【问题标题】:Uploading to Azure File Storage fails with large files大文件上传到 Azure 文件存储失败
【发布时间】:2021-01-09 20:53:49
【问题描述】:

尝试上传大于 4MB 的文件会引发 RequestBodyTooLarge 异常并显示以下消息:

The request body is too large and exceeds the maximum permissible limit.

虽然此限制记录在 REST API 参考 (https://docs.microsoft.com/en-us/rest/api/storageservices/put-range) 中,但未记录 SDK Upload* 方法 (https://docs.microsoft.com/en-us/dotnet/api/azure.storage.files.shares.sharefileclient.uploadasync?view=azure-dotnet)。也没有解决此问题的示例。

那么如何上传大文件呢?

【问题讨论】:

    标签: c# azure azure-files


    【解决方案1】:

    经过多次试验和错误,我能够创建以下方法来解决文件上传限制。在下面的代码中,_dirClient 是一个已经初始化的ShareDirectoryClient,设置为我要上传到的文件夹。

    如果传入流大于 4MB,代码会从中读取 4MB 块并上传它们直到完成。 HttpRange 是将字节添加到已上传到 Azure 的文件的位置。索引必须递增以指向 Azure 文件的末尾,以便追加新字节。

    public async Task WriteFileAsync(string filename, Stream stream) {
    
        //  Azure allows for 4MB max uploads  (4 x 1024 x 1024 = 4194304)
        const int uploadLimit = 4194304;
    
        stream.Seek(0, SeekOrigin.Begin);   // ensure stream is at the beginning
        var fileClient = await _dirClient.CreateFileAsync(filename, stream.Length);
    
        // If stream is below the limit upload directly
        if (stream.Length <= uploadLimit) {
            await fileClient.Value.UploadRangeAsync(new HttpRange(0, stream.Length), stream);
            return;
        }
    
        int bytesRead;
        long index = 0;
        byte[] buffer = new byte[uploadLimit];
    
        // Stream is larger than the limit so we need to upload in chunks
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) {
            // Create a memory stream for the buffer to upload
            using MemoryStream ms = new MemoryStream(buffer, 0, bytesRead);
            await fileClient.Value.UploadRangeAsync(ShareFileRangeWriteType.Update, new HttpRange(index, ms.Length), ms);
            index += ms.Length; // increment the index to the account for bytes already written
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果您想将较大的文件上传到文件共享或 Blob 存储,可以使用 Azure Storage Data Movement Library

      它为上传、下载更大的文件提供了高性能。请考虑将此库用于更大的文件。

      【讨论】:

      • 这看起来像使用 v11.x Microsoft.Azure.Storage.File。我目前正在使用 v12.x Azure.Storage.Files.Shares docs.microsoft.com/en-us/dotnet/api/overview/azure/…
      • 不管怎样,让这些不同的库只是为了管理远程文件共享有点令人困惑
      • @BradPatton,我的意思是,如果您专注于大文件上传/下载,您可以考虑使用它,因为该库已针对执行此类操作进行了优化。但是对于别的东西,你不需要考虑这个库:)。
      猜你喜欢
      • 1970-01-01
      • 2015-06-16
      • 1970-01-01
      • 2016-08-18
      • 2019-01-23
      • 2012-05-31
      • 2015-07-13
      • 2020-02-13
      • 1970-01-01
      相关资源
      最近更新 更多