0

OpenReadStream имеет ограничение в 500кб.Мне нужно загружать до 3мб. Поставил параметр maxAllowedsize вообще в 15мб. Загружаю два файла.Первый 350кб,второй 250кб. Прохожусь отладчиком по первой итерации в цикле.Она проходит нормально,но при второй итерации, на этом месте

await imgFile.OpenReadStream(maxAllowedsize).ReadAsync(buffers);

выключается отладчик и даже не выбрасывает исключение.Выключаются вообще любые действия на сайте.При перезагрузке страницы всё снова работает.

Проверил на 5 файлах,чей размер общий меньше 500кб и всё работает нормально. В чем может быть проблема,что всё равно файлы больше 500кб не пропускает?

Сам код

    private async Task LoadFiles(InputFileChangeEventArgs e)
{
    try
    {
        AllImgages = new();
        IBrowserFile imgFile;
        string imgurl = string.Empty;
        foreach (var files in e.GetMultipleFiles(maxAllowedFiles))
        {

            imgFile = files;
            var buffers = new byte[imgFile.Size];
            await imgFile.OpenReadStream(maxAllowedsize).ReadAsync(buffers);
            string imageType = imgFile.ContentType;
            imgurl = $"data:{imageType};base64,{Convert.ToBase64String(buffers)}";
            AllImgages.Add(new UserBlackListImage() { Img = buffers, imgURL = imgurl });

        }
    }
    catch (Exception ex)
    {

        throw;

    }
}

Для загрузки файлов использую

  <InputFile multiple OnChange="LoadFiles" class="form-control" />

Спасибо

18
  • какое значение задаёте для maxAllowedsize?
    – tym32167
    11 янв в 19:15
  • похожий вопрос на en so stackoverflow.com/a/74042356/312041
    – tym32167
    11 янв в 19:16
  • long maxAllowedsize = 1024*1024*15 11 янв в 19:17
  • дока (хз чем поможет, просто ссылки с гуглопоиска)
    – tym32167
    11 янв в 19:17
  • Я две ссылке выше уже читал и по ним пытался делать,но не работает 11 янв в 19:19

1 ответ 1

-1

https://github.com/dotnet/aspnetcore/issues/38842 Ответ можно найти в комментариях.

Мне помогло следующее

Hi all, I took another look through the repro, and that behavior is by design.

Please note per the Stream.ReadAsync docs:

The result value can be less than the number of bytes allocated in the buffer if that many bytes are not currently available, or it can be 0 (zero) if the end of the stream has been reached.

That's essentially what's happening in this case. When a single call is made to ReadAsync, it only gives you the first (few) chunks that have been sent from JS, you are not guaranteed to receive the full file. Blazor subsequently throws an error as you've only read a part of the stream and the stream subsequently times out.

The way you'd want to achieve this would be by leveraging Stream.CopyToAsync or by using Stream.ReadAsync using smaller chunks until you reach the end of the stream. Note this is in line with our streaming and file upload guidance. Specific examples and sample code are also available in those docs pages.

Note in @huseyin-ezemi's comment above, they used ReadAsByteArrayAsync, that could also work as they're allowing the whole stream to be read. Note this may pose some security & scalability concerns as you're storing the whole stream/file in memory. This approach isn't recommended.

             var fileContent = new StreamContent(e.File.OpenReadStream(1024 * 1024 * 15));
             buffer = await fileContent.ReadAsByteArrayAsync();

The above explains the behavior presented within @andrzejczar84's repro app, however in the original issue @Liero mentions running into this with CopyToAsync. This is more concerning, however I've been unable to repro. If @Liero, @angularsen or anyone else has a repro of this issue with CopyToAsync, I'd very much be interested in it. I'm marking this issue as "needs author feedback", it'll get auto-closed after a while if a repro can't be found. Though please feel free to re-open / start a new issue (and link this issue) if you do end up finding a repro with CopyToAsync.

1
  • Здесь StackOverflow на русском. Пожалуйста переведите суть ответа на русский язык.
    – aepot
    16 янв в 20:46

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.