Search code examples
javascripthtmlasp.net-coreado.net

How to get an image from user on webpage and store this image in sql server database using asp.net?


I am making a website with profiles of users and there they can upload their avatar. And I need to get a photo from user and store this in users database. First got an image from user and send information to server:

    saveButton.onclick = (() => {
        const file = photoInput.files[0];
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = (async () => {
            const bytes = reader.result;
            const description = descriptionInput.value;
            const data = JSON.stringify({
                photo: bytes,
                description
            });

            await fetch("[username]/changedata", {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json"
                },

                body: data
            });

            window.location.reload();
        });
    });

Then tried to store this image in users database:

        app.MapPut("{username}/changedata", async (string username, HttpContext context) =>
        {
            var data = await context.Request.ReadFromJsonAsync<UserDataChange>();
            using var con = new SqlConnection(connection);
            await con.OpenAsync();
            var command = new SqlCommand();
            command.Connection = con;
            command.CommandText = "UPDATE [users] " +
                                  "SET description=@description, picture=@picture " +
                                  "WHERE username=@username";
            command.Parameters.AddWithValue("username", username);
            command.Parameters.AddWithValue("description", data.Description);
            command.Parameters.AddWithValue("picture", data.Photo);
            await command.ExecuteNonQueryAsync();
            await con.CloseAsync();
        });

UserDataChange class:

public class UserDataChange
{
    public byte[] Photo { get; set; }
    public string Description { get; set; }
}

But byte[] is invalid type for this situation.


Solution

  • Usually for the processing of the avatar, because the file size is very small, I will choose to convert it into base64 format.

    How to change upload file to base64 format

    Set the picture field in the database to nvarchar(4000). If it is not enough, you can continue to increase it. Usually we will limit the size of the avatar picture, for example, it cannot be larger than 200k or 1M.

    Then after taking it out from the database, use the img tag to display it.