Blazor saveing uploaded file into database

Paul 21 Reputation points
2022-02-18T14:42:39.08+00:00

Hello Community,

i want to upload an Image with maximum size of 128Kb in my Blazor Serverside project. I heard that i terms of dataintegrity and security it would be better to save it to db. And since i only have to deal with about 20-30 Images the db would not be overload. I already created a byte[] property in my ef core entity and looked up file upload in blazor docs and found this https://learn.microsoft.com/en-us/aspnet/core/blazor/file-uploads?view=aspnetcore-6.0&pivots=server
There i read that it is not good practice to load the data stream first into a MemoryStream and read byte-array but i don't know i could transfer the bytes into my db entity without haveing it first laying around in my memory (with wouldn't be great for the other websites running on my server). Do you have any ideas for me how to solve this problem?

My Database is a PostgreSQL 12 db on an ubuntu server...

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Blazor
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2022-02-21T06:37:05.167+00:00

    Hi @Paul ,

    There i read that it is not good practice to load the data stream first into a MemoryStream and read byte-array but i don't know i could transfer the bytes into my db entity without haveing it first laying around in my memory (with wouldn't be great for the other websites running on my server). Do you have any ideas for me how to solve this problem?

    You can use the Stream.ReadAsync Method asynchronously reads a sequence of bytes from the current stream. Refer to the following sample:

    176218-image.png

    176219-image.png

    You can view the source code from here: 176272-blazorfileupload.txt

    The output is like this:

    176200-1.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.