OpenReadStream 的最大允许大小

问题描述 投票:0回答:1

OpenReadStream 的最大允许大小是多少?现在,使用 10MB。但我相信必须有一定的上限。可以带GB吗?

blazor
1个回答
8
投票

在 ASP.NET Core 5.0 中,上传文件有 2 GB 的框架文件大小限制。但是,从 ASP.NET Core 6.0 及更高版本开始,该框架不会施加最大文件大小限制。

默认情况下,允许读取大小不超过 512,000 字节 (500 KB) 的文件,否则任何进一步的读取都会导致异常。存在此限制是为了防止开发人员意外地将大文件读入内存。

await myFile.OpenReadStream().ReadAsync(buffers);

设置自定义文件上传大小,可以重写OpenReadStream方法中的maxAllowedSize参数,如下所示:

// accept a file upto 307200 bytes (300kb) of size
await myFile.OpenReadStream(maxAllowedSize: 1024 * 300).ReadAsync(buffers);

更新: 我用一个2GB大小的文件测试了文件上传,上传成功了

演示:

代码:
此 Blazor Server 代码示例已更新为适用于 .NET Framework 7 和 Visual Studio 2022,并且它使用

long
数据类型来准确表示文件大小。当处理大于 2 GB 的文件时,这是必不可少的,不能用
int
表示。

@page "/"
@using System.IO
@inject IWebHostEnvironment env

<h1 class="mb-4">Blazor Server File Upload</h1>

<div class="@AlertClass" role="alert">
    @AlertMessage
</div>

<div class="progress mb-3" style="height: 20px;">
    <div class="progress-bar" role="progressbar" style="width: @ProgressPercentage%;" aria-valuenow="@ProgressPercentage" aria-valuemin="0" aria-valuemax="100">@ProgressPercentage% Complete</div>
</div>

<form @onsubmit="OnSubmit" class="needs-validation" novalidate>
    <div class="input-group mb-3">
        <InputFile @key=@(inputFileId) class="form-control" id="inputFile" OnChange="OnInputFileChange" aria-describedby="uploadButton" required />
        <button class="btn btn-primary" type="submit" id="uploadButton" disabled="@IsUploadDisabled">
            <span class="oi oi-cloud-upload" aria-hidden="true"></span> Upload Selected File
        </button>
    </div>
    <div class="invalid-feedback">
        Please select a file to upload.
    </div>
</form>

@code {
    MarkupString AlertMessage = new MarkupString("<strong>No file selected</strong>");
    string AlertClass = "alert alert-info";
    int ProgressPercentage = 0;
    IBrowserFile selectedFile;
    long maxFileSize = 1024L * 1024L * 1024L * 2L;
    string[] allowedExtensions = { ".zip", ".rar", ".bin"};
    bool IsUploadDisabled = true;
    private Guid inputFileId = Guid.NewGuid();

    private void OnInputFileChange(InputFileChangeEventArgs e)
    {
        selectedFile = e.GetMultipleFiles()[0];
        ProgressPercentage = 0;
        IsUploadDisabled = true;

        if (selectedFile.Size > maxFileSize)
        {
            SetAlert("alert alert-danger", "oi oi-ban", $"File size exceeds the limit. Maximum allowed size is <strong>{maxFileSize / (1024 * 1024)} MB</strong>.");
            return;
        }

        if (!allowedExtensions.Contains(Path.GetExtension(selectedFile.Name).ToLowerInvariant()))
        {
            SetAlert("alert alert-danger", "oi oi-warning", $"Invalid file type. Allowed file types are <strong>{string.Join(", ", allowedExtensions)}</strong>.");
            return;
        }

        SetAlert("alert alert-info", "oi oi-info", $"<strong>{selectedFile.Name}</strong> ({selectedFile.Size} bytes) file selected.");
        IsUploadDisabled = false;
    }

    private async void OnSubmit()
    {
        if (selectedFile != null)
        {
            IsUploadDisabled = true;
            Stream stream = selectedFile.OpenReadStream(maxFileSize);
            var path = $"{env.WebRootPath}\\{selectedFile.Name}";
            using FileStream fs = File.Create(path);

            // Set buffer size to 512 KB.
            int bufferSize = 512 * 1024;
            byte[] buffer = System.Buffers.ArrayPool<byte>.Shared.Rent(bufferSize);
            int bytesRead;
            long totalBytesRead = 0;
            long fileSize = selectedFile.Size;

            // Use a timer to update the UI every few hundred milliseconds.
            using var timer = new Timer(_ => InvokeAsync(() => StateHasChanged()));
            timer.Change(TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(500));

            try
            {
                while ((bytesRead = await stream.ReadAsync(buffer)) != 0)
                {
                    totalBytesRead += bytesRead;
                    ProgressPercentage = (int)(100 * totalBytesRead / fileSize);
                    await fs.WriteAsync(buffer, 0, bytesRead);
                }
            }
            finally
            {
                System.Buffers.ArrayPool<byte>.Shared.Return(buffer);
            }

            // Stop the timer and update the UI with the final progress.
            timer.Change(Timeout.Infinite, Timeout.Infinite);
            ProgressPercentage = 100;
            SetAlert("alert alert-success", "oi oi-check", $"<strong>{selectedFile.Name}</strong> ({selectedFile.Size} bytes) file uploaded on server.");
            inputFileId = Guid.NewGuid();
            this.StateHasChanged();
        }
    }

    private void SetAlert(string alertClass, string iconClass, string message)
    {
        AlertClass = alertClass;
        AlertMessage = new MarkupString($"<span class='{iconClass}' aria-hidden='true'></span> {message}");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.