问题
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