'How to get Image to display in ASP.net app?
I'm trying to get a webpage to display an image on my disk, using a string from a database, the html I am using for it is thus
<div id="userProfileImage" style="background-image: url(@Model.ProfileImage);"></div>
The model in question would reffer to the following code,
public async Task<IActionResult> DetailAsync(string id)
{
var user = _userService.GetById(id);
var userRoles = await _userManager.GetRolesAsync(user);
var model = new ProfileModel
{
UserId = user.Id,
UserName = user.UserName,
UserRating = user.Rating,
DisplayName = user.DisplayName,
Email = user.Email,
ProfileImage = user.UserImage,
MemberSince = user.MemberSince,
IsAdmin = userRoles.Contains("Admin")
};
return View(model);
}
[HttpPost]
public async Task<IActionResult> UploadProfileImage (IFormFile file)
{
var userId = _userManager.GetUserId(User);
if (UploadFile(file))
{
var fileName = Path.GetFileName(file.FileName);
var filePathUpload = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images\profiles", fileName);
var filePathDb = Path.Combine(@"\images\profiles", fileName);
using (var fileStream = new FileStream(filePathUpload, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
await _userService.SetProfileImage(userId, filePathDb);
}
return RedirectToAction("Detail", "Profile", new { id = userId });
}
However, no image is displaying. When using debug, the ProfileImage field in model returns "\images\profiles\defualtProfileImage.jpg", which should point to a path in my wwwroot folder. But it's not displaying. Would anyone have any ideas on how to fix it?
Solution 1:[1]
The following:
var filePathDb = Path.Combine(@"\images\profiles", fileName);
Needed to be:
var filePathDb = @$"/images/profiles/{fileName}"
The \s were interfering with the file name being looked for, but were correct for saving the image to the correct place on the hard drive.
Thank you contributor @David for pointing me in the direction of the network tab of inspect element.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeremy Caney |
