上传到 Azure 文件存储因大文件而失败

Bra*_*ton 2 c# azure azure-files

尝试上传大于 4MB 的文件会导致RequestBodyTooLarge抛出异常并显示以下消息:

The request body is too large and exceeds the maximum permissible limit.
Run Code Online (Sandbox Code Playgroud)

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

那么如何上传大文件呢?

Bra*_*ton 15

经过多次试验和错误,我能够创建以下方法来解决文件上传限制。下面的代码中是我要上传到的文件夹的_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
    }
}
Run Code Online (Sandbox Code Playgroud)