首页 > 解决方案 > Asp.Net Core 3.1 - 从目录中获取图像并在剃刀视图中显示?

问题描述

如何从目录中获取图像并显示它?

“我看到了类似的帖子,但没有帮助”

我这样做了,但没有用

控制器 :

     string[] filePaths = Directory.GetFiles(Path.Combine(_hostingEnv.WebRootPath, @"site\img\banner\"));          
       
        ViewBag.ListImgMainDefalt = filePaths;

看法 :

foreach (var item in ViewBag.ListImgMainDefalt)
                    {
                        <tr>                               

                            <td>
                                <img src="@item" />
                            </td>
                        </tr>

                    }

结果: 在此处输入图像描述

标签: htmlasp.netimageasp.net-corerazor-pages

解决方案


更改您的代码,如下所示:

string[] filePaths = Directory.GetFiles(Path.Combine(_hostingEnv.WebRootPath, @"site\img\banner\"));
List<string> fileName = new List<string>();
foreach (string filePath in filePaths)
{
    fileName.Add(@"/site/img/banner/"+Path.GetFileName(filePath));
}
ViewBag.ListImgMainDefalt = fileName;

推荐阅读