How to show images from a folder using Razor MVC?

2019-04-29 05:37发布

I am using Razor MVC and I would like to show images from "~/Content/uploads" folder. I came up with the following solution:

@foreach (FileInfo fileInfo in (new DirectoryInfo(Server.MapPath("~/Content/uploads"))
                                    .GetFiles().Where(x => x.Extension == ".jpg"))) {
    <img src="/@fileInfo
               .FullName
               .Substring(Server.MapPath("~/").Length)
               .Replace("\\", "/")"
         width="100">
}

The problem with the code is that I am taking the full file path and I am removing the Server.MapPath() prefix.

How can I simplify this code?

2条回答
Rolldiameter
2楼-- · 2019-04-29 06:25

You can use the UrlHelper class that is available on Razor pages.

@foreach (var imgPath in Directory.GetFiles(Server.MapPath("~/Content/uploads"), "*.jpg"))
{
    var img = new FileInfo(imgPath);
    <img src="@Url.Content(String.Format("~/Content/uploads/{0}", img.Name))" />
}
查看更多
一夜七次
3楼-- · 2019-04-29 06:25

@Rowan Freeman answer helped me for jpg image file. But This is for multiple files:

View images with multiple filters

@{

string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.ico";

foreach (string imgPath in Directory.GetFiles(Server.MapPath("~/images/store/"), "*.*", 
SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s)
.ToLower())))
{
    var img = new FileInfo(imgPath);
    <img style="width: 200px; height: 200px;" src="@Url.Content(String.Format("~/images/
    store/{0}", img.Name))" />
}

}

Hope helps some one.

Reference

查看更多
登录 后发表回答