动态地在文件夹ASP.NET核心中显示图像



我试图在我存储在根文件中的图像文件夹中显示所有图像。我知道他们已经在asp.net core中拱上了server.mappath方法。我不确定如何在创建视图模型的.NET核心中执行相同的功能,并能够循环浏览存储在我的root Image文件夹中的所有图像。任何建议都很棒。以下是我要使用的示例代码,但显然对.net核心不起作用。

// model
class MyViewModel
{
    public IEnumerable<string> Images { get; set; }
}
// controller
public ActionResult MyAction()
{
    var model = new MyViewModel()
{
    Images = Directory.EnumerateFiles(Server.MapPath("~/images_upload"))
                      .Select(fn => "~/images_upload/" + 
   Path.GetFileName(fn))
};
return View(model);
}
// view
@foreach(var image in Model.Images)
  {
     <img src="@Url.Content(image)" alt="Hejsan" />
  }

您需要使用IHostingEnvironment,如果将其指定在构造函数中,则应将其注入控制器。

然后,您可以使用属性(取决于放置images_upload文件夹的位置):

  • ContentRootPath - 应用程序的基本路径。这是web.config,project.json
  • WebRootPath - 物理文件路径包含旨在浏览的文件的目录。默认情况下,这是wwwroot文件夹

然后使用System.IO.Path.Combine()

例如。

public class HomeController : Controller
{
    private IHostingEnvironment _env;
    public HomeController(IHostingEnvironment env)
    {
        _env = env;
    }
    public ActionResult MyAction()
    {
        var folderPath = System.IO.Path.Combine(_env.ContentRootPath, "/images_upload");
        var model = new MyViewModel()
        {
            Images = Directory.EnumerateFiles(folderPath)
                .Select(filename => folderPath + filename)
        };
        return View(model);
    }
}

最新更新