asp.net core RC2 image does not display

折月煮酒 提交于 2020-01-25 12:42:16

问题


What I am trying to do is to display an image from web root folder and this is the way I am trying to do it:

The following class is just experimental and is just and example for me to try it out. For now there is only one image in the folder that is being read from. As well the rootPath is taken from: _hostingEnvironment.WebRootPath

 public class GetRandomImageForGalleryView : IGetRandomImageFromFolder
    {
        private string rootPath;
        public GetRandomImageForGalleryView(string rootPath)
        {
            this.rootPath = rootPath;
        }
        public string[] getImage()
        {
            return ReadPhotosFromDirectory();
        }
        private string[] ReadPhotosFromDirectory()
        {

            string[] fileLocations = Directory.GetFiles(rootPath+"\\lib\\Images\\Nature");
            return fileLocations;
        }
    }

And this is the way I am trying to display it:

@model IGetRandomImageFromFolder
@{ 
    ViewBag.Title = "Gallery";
}
<div class="container">
    <div class="row">
        @{
            foreach (string item in Model.getImage())
            {
                <img src="@item" alt="Image" />
            }
        }
    </div>
</div>

However there is no output, even if I change it to <img src="@Url.Content(item)" alt="Image" /> Still nothing is happening.

If I just output @item it will display the path to the image. The app.UseStaticFiles(); has been added as well.

So my question is what am I doing wrong, am I missing something? And how to do it properly?


回答1:


Create a folder for images in wwwroot folder and you can access image with this

<img src="~/images/123.jpg" />

or using url.content

  <img src='@Url.Content("~/images/123.jpg" )'/>



回答2:


It allows only files under wwwroot folder. So underneath path only has to mention. Attached example snapshot.



来源:https://stackoverflow.com/questions/38147178/asp-net-core-rc2-image-does-not-display

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!