Reputation: 3
I want to show image in view from database. I store the image path in database so I want to give that path to img src=""
but it does not work. Code is following:
The following code is in view
@{
var FileName = db.UserImages.FirstOrDefault(x => x.UserID == User.Identity.Name).ImgName;
var serverpath = Server.MapPath("~/App_Data/ProfileImages/");
string filename = Path.GetFileName(FileName);
string fullpath = Path.Combine(serverpath, filename);
ViewBag.fullpath = fullpath;
}
<img src="@Url.Content("~/App_Data/ProfileImages/" + System.IO.Path.GetFileName(ViewBag.fullpath))" class="user-image" alt="User Image">
The image does not loaded where path is correct but it does not work
Upvotes: 0
Views: 584
Reputation: 615
The Server.MapPath call will give you a server based file path, ie something like c:\websites\mywebsite\App_Data\ProfileImages, which normally isn't accessable via the web.
From you snippet of code, it appears you just need to combine the cleaned FileName retrieved from the database with ~/App_Data/ProfileImages/
@{
var FileName = db.UserImages.FirstOrDefault(x => x.UserID == User.Identity.Name).ImgName;
string filename = Path.GetFileName(FileName);
}
<img src="@Url.Content("~/App_Data/ProfileImages/" + filename)" class="user-image" alt="User Image">
edit: App_Data is a special protected folder that IIS will not serve files from unless configured to do so, look at system.webServer/security/requestFiltering/hiddenSegments
Upvotes: 0
Reputation: 18973
Use absolute path is not good practice for image URL.
You should configure image path in web config
or move image to a CDN
and use it.
In web config
<appSettings>
<add key="BaseImageUrl" value="/Content/Images" />
</appSettings>
In cshtml
@{
var FileName = db.UserImages.FirstOrDefault(x => x.UserID == User.Identity.Name).ImgName;
var baseUrl = ConfigurationManager.AppSettings["BaseImageUrl"];
var imagePath = string.Format("{0}/{1}", baseUrl, FileName);
}
<img src="@imagePath" class="user-image" alt="User Image"/>
You also should move code to get FileName to controller or Service layer should not code in UI layer.
Upvotes: 0
Reputation: 77926
Shouldn't it just be below since your fullpath
essentially contains the whole path of the said image file
<img src="@Url.Content(ViewBag.fullpath)" class="user-image" alt="User Image">
Upvotes: 1