简体   繁体   中英

Get image from wwwroot/images in ASP.Net Core

I have an image in wwwroot/img folder and want to use it in my server side code.

How can I get the path to this image in code?

The code is like this:

Graphics graphics = Graphics.FromImage(path)

It would be cleaner to inject an IHostingEnvironment and then either use its WebRootPath or WebRootFileProvider properties.

For example in a controller:

private readonly IHostingEnvironment env;
public HomeController(IHostingEnvironment env)
{
    this.env = env;
}

public IActionResult About(Guid foo)
{
    var path = env.WebRootFileProvider.GetFileInfo("images/foo.png")?.PhysicalPath
}

In a view you typically want to use Url.Content("images/foo.png") to get the url for that particular file. However if you need to access the physical path for some reason then you could follow the same approach:

@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment env
@{ 
 var path = env.WebRootFileProvider.GetFileInfo("images/foo.png")?.PhysicalPath
}

Building on Daniel's answer, but specifically for ASP.Net Core 2.2:

Use dependency injection in your controller:

[Route("api/[controller]")]
public class GalleryController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;
    public GalleryController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }        

    // GET api/<controller>/5
    [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        var path = Path.Combine(_hostingEnvironment.WebRootPath, "images", $"{id}.jpg");
        var imageFileStream = System.IO.File.OpenRead(path);
        return File(imageFileStream, "image/jpeg");
    }
}

A concrete instance of the IHostingEnvironment is injected into your controller, and you can use it to access WebRootPath (wwwroot).

FYI.Just an update to this. In ASP.NET Core 3 & Net 5 it's the following:

    private readonly IWebHostEnvironment _env;

    public HomeController(IWebHostEnvironment env)
    {
        _env = env;

    }

    public IActionResult About()
    {
      var path = _env.WebRootPath;
    }

This works:

private readonly IHostingEnvironment env;
public HomeController(IHostingEnvironment env)
{
    this.env = env;
}

public IActionResult About()
{
    var stream = env.WebRootFileProvider.GetFileInfo("image/foo.png").CreateReadStream();
    System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
    Graphics graphics = Graphics.FromImage(image);
}
 string path =  $"{Directory.GetCurrentDirectory()}{@"\wwwroot\images"}";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM