ASP.Net MVC - Img Src Server Path

Visual Studio 2012 - ASP.net - MVC 4

I am having problems displaying an image from the path to the server that is stored in the database.

I use HttpPostedFileBase to retrieve the file that the user uploaded:

using (var uow = _db.CreateUnitOfWork()) { if (imageUpload != null && imageUpload.ContentLength > 0) { var fileName = Path.GetRandomFileName() + Path.GetExtension(imageUpload.FileName); var path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads"), fileName); imageUpload.SaveAs(path); achievement.ImageLoc = path; } uow.Add(achievement); Save(uow); return true; } 

This will save the absolute path of the downloaded file to the database and save the file on the server. When I try to get this path to display the image file in the view, all I get is an empty square, as this file is not found (near: empty when right-click β†’ copy image URL). I know the path is correct because I use it in a different view so that users can upload files that work correctly. I also allow the user to edit the file, which successfully deletes the old one and loads the new one. The only problem I am facing is to show the image in the view.

I tried:

 <img src="@Html.Encode(Model.ImageLoc)" /> <img src=@Url.Content (Model.ImageLoc)" /> 

Can anyone suggest anything?

+4
source share
2 answers

You have saved the absolute path to the image in your database, but you need to reference it with a relative path:

 <img src="@Url.Content("~/Uploads/" + System.IO.Path.GetFileName(Model.ImageLoc))" alt="" /> 

The HTML result should look like this:

 <img src="/Uploads/tccxdfu0.nde.jpg" alt="" /> 

and not:

 <img src="\\PDC2\sites\t\<site.co.uk>\public_html\Uploads\tccxdfu0.nde.jpg" alt="" /> 

because the client cannot access these folders from the server.

+12
source

Look at using

http://msdn.microsoft.com/en-us/library/system.web.mvc.mvchtmlstring%28VS.100%29.aspx I suspect it is encoded, so it doesn’t output as you expect.

0
source

Source: https://habr.com/ru/post/1438690/


All Articles