简体   繁体   English

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

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

I am trying to display all the images in a images folder I have stored in the root file. 我试图显示所有存储在根文件中的图像文件夹中的图像。 I know they have vaulted the Server.MapPath method in asp.net core. 我知道他们已经在asp.net核心中存储了Server.MapPath方法。 I am not sure how I would do the same functionality in .net core of creating a view model and being able to loop through all the images stored in my root images folder. 我不确定如何在.net核心中执行相同的功能,即创建视图模型并能够遍历存储在根图像文件夹中的所有图像。 Any suggestions would be great. 任何建议都很好。 Below is the example code I was going off of but it obviously doesn't work for.Net core. 以下是我要使用的示例代码,但显然不适用于.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" />
  }

You need to use IHostingEnvironment , which you should get injected into your Controller if you specify it in the constructor. 您需要使用IHostingEnvironment ,如果在构造函数中指定它,则应将其注入Controller中。

You can then use the properties (depending on where you put your images_upload folder): 然后,您可以使用属性(取决于放置images_upload文件夹的位置):

  • ContentRootPath - application's base path. ContentRootPath-应用程序的基本路径。 This is the location of the web.config, project.json 这是web.config,project.json的位置
  • WebRootPath - the physical file path to the directory that houses files intended to be browsable. WebRootPath-存放打算浏览的文件的目录的物理文件路径。 By default, this is the wwwroot folder 默认情况下,这是wwwroot文件夹

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

eg 例如

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