【问题标题】:how to show all images from server directory in asp.net core如何在asp.net核心中显示服务器目录中的所有图像
【发布时间】:2017-05-25 12:21:17
【问题描述】:

我想在 asp.net mvc 5 中显示所有图像(位于 "~/files/ " 文件夹中)。就像这样:

public ActionResult uploadPartial()
{
     var appData = Server.MapPath("~/files");
     var images = Directory.GetFiles(appData).Select(x => new imagesviewmodel
     {
        Url = Url.Content("/files/" + Path.GetFileName(x))
     });
     return View(images);
} 

在视野中

@model IEnumerable<ckeditortest.Models.imagesviewmodel>

@foreach (var image in Model)
{
    <a href="#" class="returnImage" data-url="@Request.Url.GetLeftPart(UriPartial.Authority)@image.Url">
        <img src="@image.Url" alt="Hejsan" id="#image" data-source="@image.Url" width="200" height="200"/>
    </a>
}

但是在 asp.net core 中我不知道该怎么做

【问题讨论】:

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


    【解决方案1】:

    你想要Directory.EnumerateFiles。有关示例,请参阅this answer。您还必须替换 Server.MapPath,因为它在 .NET Core 中不可用。您可以使用this code 来执行此操作(注入IHostingEnvironment 并从中获取WebRootPath)。

    使用上述两种方法,您将获得以下代码(未经测试):

    public class MyController : Controller
    {
        private IHostingEnvironment _env;
    
        public HomeController(IHostingEnvironment env)
        {
            _env = env;
        }
    
        public IActionResult Index()
        {
            var webRoot = _env.WebRootPath;
            var appData = System.IO.Path.Combine(webRoot, "files");
    
            var models = Directory.EnumerateFiles(appData).Select(x => new imagesviewmodel
            {
                Url = Url.Content(x)
            });
    
            return View(models);
        }
    }
    

    你可以用这个替换GetLeftPart(来自this answer):

    Request.Url.GetComponents(UriComponents.Scheme | UriComponents.StrongAuthority, UriFormat.Unescaped)
    

    【讨论】:

    • 感谢您的回答!我会尽快测试它。另一个问题如何在视图中更改此代码@Request.Url.GetLeftPart(UriPartial.Authority)@image.Url ----?对于 asp.net 核心
    • @FatikhanGasimov 我已经用该信息更新了答案。
    • Request.Url.GetComponents(UriComponents.Scheme | UriComponents.StrongAuthority, UriFormat.Unescaped) 不起作用
    猜你喜欢
    • 1970-01-01
    • 2012-06-12
    • 2012-07-02
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    相关资源
    最近更新 更多