Blazor: Save uploaded file directly to entity object

Viewed 842

I have a blazor server app and need to enable uploading image files to then save them to a database. The database is being accessed via entity framework core, i.e. the provided entity objects. For uploading I am using the blazor InputFile component.

Usually I would read the entire image as byte array and then save it via the ef core entity object like that:

    private async void ImageUpload(InputFileChangeEventArgs e)
    {
        MemoryStream ms = new MemoryStream();
        await e.File.OpenReadStream().CopyToAsync(ms);
        myEntityObject.ImageData = ms.ToArray();
    }

However, the microsoft documentation strongly recommends not using that approach and to never read the whole file to memory: Source

Avoid reading the incoming file stream directly into memory. For example, don't copy file bytes into a MemoryStream or read as a byte array. These approaches can result in performance and security problems, especially in Blazor Server. Instead, consider copying file bytes to an external store, such as a blob or a file on disk. If you need access to a Stream that represents the file's bytes, use IBrowserFile.OpenReadStream.

Is it even possible to not read the whole file as a memory stream? In my understanding, if I want to save the file via the entity object, all the data will always be present in memory. Am I missing something?

0 Answers
Related