我在wwwroot / img文件夹中有一个图像,想在我的服务器端代码中使用它。
如何在代码中获取此图像的路径?
代码是这样的:
Graphics graphics = Graphics.FromImage(path)
答案 0 :(得分:7)
注入IHostingEnvironment
然后使用其WebRootPath
或WebRootFileProvider
属性会更清晰。
例如在控制器中:
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
}
在视图中,您通常希望使用Url.Content("images/foo.png")
来获取该特定文件的网址。但是,如果由于某种原因需要访问物理路径,那么您可以采用相同的方法:
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment env
@{
var path = env.WebRootFileProvider.GetFileInfo("images/foo.png")?.PhysicalPath
}
答案 1 :(得分:2)
基于Daniel的答案,但专门针对ASP.Net Core 2.2:
在控制器中使用依赖项注入:
[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");
}
}
将IHostingEnvironment的具体实例注入到您的控制器中,您可以使用它来访问WebRootPath(wwwroot)。
答案 2 :(得分:0)
这有效:
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);
}
答案 3 :(得分:0)
仅供参考。只需对此进行更新。在ASP.NET Core 3和Net 5中为:
private readonly IWebHostEnvironment _env;
public HomeController(IWebHostEnvironment env)
{
_env = env;
}
public IActionResult About()
{
var path = _env.WebRootPath;
}
答案 4 :(得分:-2)
string path = $"{Directory.GetCurrentDirectory()}{@"\wwwroot\images"}";