asp.net-mvc ASP.Net MVC - Img Src 服务器路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12803659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.Net MVC - Img Src Server Path
提问by Jpin
Visual Studio 2012 - ASP.net - MVC 4
Visual Studio 2012 - ASP.net - MVC 4
I am having troubles displaying an image from a server path which is stored in a database.
我在显示来自存储在数据库中的服务器路径的图像时遇到问题。
I am using HttpPostedFileBase to retrieve the file the user has uploaded:
我正在使用 HttpPostedFileBase 来检索用户上传的文件:
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 uploaded file into the database and save the file onto the server. When I try to retrieve this path to display an image file in a view all I get is a blank square like the file is not being found (about:blank when right click -> copy image url). I know the path is correct because I am using it in a different view to allow users to download files, which is working correctly. Also I am allowing the user to edit the file which successfully deletes the old and uploads a new one. The only problem I am having is displaying an image in a view.
这会将上传文件的绝对路径保存到数据库中,并将文件保存到服务器上。当我尝试检索此路径以在视图中显示图像文件时,我得到的只是一个空白方块,就像未找到该文件一样(about:blank when right click -> copy image url)。我知道路径是正确的,因为我在不同的视图中使用它来允许用户下载文件,这是正常工作的。此外,我允许用户编辑成功删除旧文件并上传新文件的文件。我遇到的唯一问题是在视图中显示图像。
I have tried:
我试过了:
<img src="@Html.Encode(Model.ImageLoc)" />
<img [email protected](Model.ImageLoc)" />
Would anyone be able to suggest anything?
任何人都可以提出任何建议吗?
回答by Darin Dimitrov
You have stored the absolute path to the image in your database, but you need to reference it with the relative path:
您已将图像的绝对路径存储在数据库中,但您需要使用相对路径来引用它:
<img src="@Url.Content("~/Uploads/" + System.IO.Path.GetFileName(Model.ImageLoc))" alt="" />
The resulting HTML must look like this:
生成的 HTML 必须如下所示:
<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 such folders from the server.
因为客户端无法从服务器访问此类文件夹。
回答by RubbleFord
Look at using
看使用
http://msdn.microsoft.com/en-us/library/system.web.mvc.mvchtmlstring%28VS.100%29.aspxI suspect it's being encoded hence not outputting as you expect.
http://msdn.microsoft.com/en-us/library/system.web.mvc.mvchtmlstring%28VS.100%29.aspx我怀疑它已被编码,因此没有按预期输出。

