'ASP.NET Core how to upload image to SQL Server database?
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 class="col-md-4">
<form asp-action="AddUser" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
/*some more code here for other members*/
<div class="form-group">
<label asp-for="UserPicture" type="file"class="control-label">User Picture</label>
<input asp-for="UserPicture" type="file" class="form-control" />
<span asp-validation-for="UserPicture" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</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 class="form-group">
<label asp-for="imgfile" type="file"class="control-label">User Picture</label>
<input asp-for="imgfile" type="file" class="form-control" />
<span asp-validation-for="imgfile" class="text-danger"></span>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
