【发布时间】:2017-07-24 01:38:11
【问题描述】:
我在 wwwroot/img 文件夹中有一个图像,并想在我的服务器端代码中使用它。
如何在代码中获取此图像的路径?
代码是这样的:
Graphics graphics = Graphics.FromImage(path)
【问题讨论】:
标签: c# asp.net-core asp.net-core-mvc asp.net-core-webapi
我在 wwwroot/img 文件夹中有一个图像,并想在我的服务器端代码中使用它。
如何在代码中获取此图像的路径?
代码是这样的:
Graphics graphics = Graphics.FromImage(path)
【问题讨论】:
标签: c# asp.net-core asp.net-core-mvc asp.net-core-webapi
仅供参考。只是对此的更新。在 ASP.NET Core 3 和 Net 5 中如下:
private readonly IWebHostEnvironment _env;
public HomeController(IWebHostEnvironment env)
{
_env = env;
}
public IActionResult About()
{
var path = _env.WebRootPath;
}
【讨论】:
这行得通:
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);
}
【讨论】:
以 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)。
【讨论】:
注入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") 来获取该特定文件的 url。但是,如果您出于某种原因需要访问物理路径,则可以采用相同的方法:
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment env
@{
var path = env.WebRootFileProvider.GetFileInfo("images/foo.png")?.PhysicalPath
}
【讨论】:
string path = $"{Directory.GetCurrentDirectory()}{@"\wwwroot\images"}";
【讨论】:
Directory.GetCurrentDirectory 在部署到 IIS 等服务器时可能会not return what you expect。