IFormFile 'System.InvalidOperationException'

asp.net-core entity-framework-core iformfile razor-pages


The non-public.member _baseStream attribute in IFormFile in my ASP.NET Core application throws the following exception after uploading a file:

ReadTimeout =   ((Microsoft.AspNetCore.Http.Internal.FormFile)BildUpload)._baseStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

I'm trying to upload a file using a razor page with the following code:

<form method="post" enctype="multipart/form-data">
    <div class="form-group">
        <input type="file" name="BildUpload"  />
    <input type="submit" value="Upload" class="btn btn-default" />

In the codebehind class I only got the declaration and nothing else read or writes the paramter excepts the razor page:

    public IFormFile BildUpload { get; set; }

Thanks for your help!

My final goal is to parse the file to a byte array and sava at to a database like this: How to Convert a file into byte array directly without its path(Without saving file) But over there I'm getting a nullpointer exception.

10/9/2018 9:49:33 AM

Accepted Answer

In case someone faces similar behavior. Here's my solution for uploading an image and converting it to a byte array (for storing it in a Microsoft SQL database):

First of all use the xaml code and the IFormFile property from the question. In the code behind add this code to process the form data to a byte array:

public async Task<IActionResult> OnPostAsync(string id)
    //get the "Kontakt" entity
    if (!await SetKontaktAsync(id))
          return NotFound();

    //convert form data to byte array and assign it to the entity
    if (BildUpload.Length > 0)
          using (var ms = new MemoryStream())
                Kontakt.Bild = ms.ToArray();

    //save changes to the database
    _context.Attach(Kontakt).State = EntityState.Modified;
    await _context.SaveChangesAsync();

    //reload page
    return await OnGetAsync(Kontakt.GID);

Frameworks: ASP.NET Core 2.2, Entity Framework Core 2.2

3/27/2019 2:12:02 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow