Rockj
Rockj

Reputation: 97

How to return an image from wwwroot?

I'm trying to return an image stored inside wwwwroot/images folder, this is the structure:

enter image description here

Inside the View I have the following tag:

<img src="@Url.Action("GetAvatar", "User", new { username = User.Identity.Name })" />

as you can see for display the image it simply call GetAvatar method from User controller passing the username as parameter.

The method have the following configuration:

[HttpGet]
public FileResult GetAvatar(string username)
{
   User user = _repo.GetUser(username);

   if(user.UserDetail != null)
      return File(user.UserDetail?.UserPhoto, "image/png");

   //The user has no custom image, will displayed the default.
   string root = Path.Combine(_env.WebRootPath, "images");

   return File(Path.Combine(root, "avatar_default.png"), "image/png");
}

the firtst part of the method that retrieve the image from the database works, but the last part which try to get the image from the wwwroot folder doesn't work. Infact when I load the View I get the broked thumbnail which mean not found.

I'm also injected the IHostingEnvironment for access to wwwroot folder.

Any idea?

Upvotes: 1

Views: 674

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93273

The File method you're using has the following signature:

public VirtualFileResult File (string virtualPath, string contentType);

As its name suggests, the first parameter here represents the virtual path of the file you want to serve; not the physical path. By default, this means you need to provide a path that is essentially just relative to the wwwroot folder. In your example, the path would be images/avatar_default.png. With this, there's no need for Path.Combine or IHostingEnvironment in your example. Here's the updated version:

[HttpGet]
public FileResult GetAvatar(string username)
{
   User user = _repo.GetUser(username);

   if(user.UserDetail != null)
      return File(user.UserDetail?.UserPhoto, "image/png");

   return File("images/avatar_default.png", "image/png");
}

Upvotes: 1

Related Questions