Home > Software engineering >  ASP.NET Core how to upload image to SQL Server database?
ASP.NET Core how to upload image to SQL Server database?

Time:02-16

I am trying to do a simple app to register users to a database with name, surname, profile photo etc. then edit or delete them. I am planning to upload the image as IFileForm, then convert it to varbinary for SQL Server. But I am having a problem on how to implement uploading the image. The code works for other members. Any help would be appreciated.

My user model class for API

public partial class User
{
    public string UserId { get; set; };
    public string UserName { get; set; };
    public string UserSurname { get; set; };
    public string UserBirthdate { get; set; };
    public byte[] UserPicture { get; set; };
}

Post method for my API

public async Task<ActionResult<User>> PostUser(User user)
{
    _context.UserTable1s.Add(user);

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateException)
    {
        if (UserExists(user.UserId))
        {
             return Conflict();
        }
        else
        {
            throw;
        }
    } 

    return CreatedAtAction("GetUser", new { id = user.UserId }, user);
}

My user model for Web App

public class User
{
    public string UserId { get; set; }
    public string UserName { get; set; }
    public string UserSurname { get; set; }
    public string UserBirthdate { get; set; }
    public IFormFile UserPicture { get; set; }
}

Post method for Web App to consume API

public async Task<IActionResult> AddUser(User user)
{
    User receivedUser = new User();

    using (var httpClient = new HttpClient())
    {
        StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");

        using (var response = await httpClient.PostAsync("https://localhost:7252/api/Users", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            receivedUser = JsonConvert.DeserializeObject<User>(apiResponse);
        }
    }

    return View(receivedUser);
}

And finally the view for AddUser. Removed the code for other members because too long.

 <div >
        <form asp-action="AddUser" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" ></div>
            /*some more code here for other members*/
            <div >
                <label asp-for="UserPicture" type="file">User Picture</label>
                <input asp-for="UserPicture" type="file"  />
                <span asp-validation-for="UserPicture" ></span>
            </div>
            <div >
                <input type="submit" value="Create"  />
            </div>
        </form>
    </div>

EDIT: I managed to make it work after editing vega_gf's answer a little. I am pretty sure it is not the most optimal way but it works for now.

My AddUser method now:

public async Task<IActionResult> AddUser(User user, [FromForm]IFormFile imgfile)
{
    User receivedUser = new User();
    using (var httpClient = new HttpClient())
    {
            if (imgfile != null)
            {
                using var dataStream = new MemoryStream();
                await imgfile.CopyToAsync(dataStream);
                byte[] imageBytes = dataStream.ToArray();
                string base64String = Convert.ToBase64String(imageBytes);
                user.UserPicture = base64String;
            }
        
        StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");

        using (var response = await httpClient.PostAsync("https://localhost:7252/api/Users", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            receivedUser = JsonConvert.DeserializeObject<User>(apiResponse);
        }
    }
    return View(receivedUser);
}

Added an IFormFile imgfile property to my model and used it in view like this:

<div >
                <label asp-for="imgfile" type="file">User Picture</label>
                <input asp-for="imgfile" type="file"  />
                <span asp-validation-for="imgfile" ></span>
            </div>

CodePudding user response:

First I would change image type to string(optional)

Then on your AddUser method you add this

[BindProperty]
public IFormFile ImageFile { get; set; }
public string Msg { get; set; }  
public static readonly List<string> ImageExtensions = new() { ".JPG", ".BMP", ".PNG" }; //to restrict file extensions


if (HttpContext.Request.Form.Files.Count > 0)// check if the user uploded something
{
     ImageFile = HttpContext.Request.Form.Files.GetFile("file_Main");
     if (ImageFile != null)
     {
          var extension = Path.GetExtension(ImageFile.FileName);//get file name
          if (ImageExtensions.Contains(extension.ToUpperInvariant()))
          {
              using var dataStream = new MemoryStream();
              await ImageFile.CopyToAsync(dataStream);
              byte[] imageBytes = dataStream.ToArray(); // you can save this to your byte array variable and remove the 2 lines below
              string base64String = Convert.ToBase64String(imageBytes);
              User.UserPicture = base64String; // to save the image as base64String 
              }
              else
              {
                  Msg = "image format must be in JPG, BMP or PNG"; //Custom error message
                  return Page();
              }
          }
      }
}

on your view just add this

@if (Model.User.UserPicture != null)
{
    <img src="data:image/png;base64,@Html.DisplayFor(model => model.User.UserPicture)" height="40" width="40">
}
  • Related