【问题标题】:Displaying Images in folder asp.net core dynamically动态显示文件夹 asp.net core 中的图像
【发布时间】:2018-12-19 15:47:12
【问题描述】:

我正在尝试显示存储在根文件中的图像文件夹中的所有图像。我知道他们已经在 asp.net 核心中使用了 Server.MapPath 方法。我不确定如何在 .net 核心中执行相同的功能来创建视图模型并能够遍历存储在我的根图像文件夹中的所有图像。任何建议都会很棒。下面是我要使用的示例代码,但它显然不适用于.Net core。

// 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" />
  }

【问题讨论】:

    标签: c# .net asp.net-core asp.net-core-mvc


    【解决方案1】:

    您需要使用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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 2019-05-30
      • 2016-11-03
      相关资源
      最近更新 更多