繁体   English   中英

在文件夹asp.net核心中动态显示图像

[英]Displaying Images in folder asp.net core dynamically

我试图显示所有存储在根文件中的图像文件夹中的图像。 我知道他们已经在asp.net核心中存储了Server.MapPath方法。 我不确定如何在.net核心中执行相同的功能,即创建视图模型并能够遍历存储在根图像文件夹中的所有图像。 任何建议都很好。 以下是我要使用的示例代码,但显然不适用于.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 ,如果在构造函数中指定它,则应将其注入Controller中。

然后,您可以使用属性(取决于放置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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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