ASP.Net MVC-图Src服务器路径 [英] ASP.Net MVC - Img Src Server Path

查看:179
本文介绍了ASP.Net MVC-图Src服务器路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

我正在使用HttpPostedFileBase来检索用户已上传的文件:

I am using HttpPostedFileBase to retrieve the file the user has 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;
            }

这会将上载文件的绝对路径保存到数据库中,并将文件保存到服务器上.当我尝试检索此路径以在视图中显示图像文件时,得到的只是一个空白方块,就像找不到该文件一样(右键单击->复制图像URL时大约为空白).我知道路径是正确的,因为我在不同的视图中使用它来允许用户下载文件,这可以正常工作.另外,我允许用户编辑成功删除旧文件并上传新文件的文件.我唯一的问题是在视图中显示图像.

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.

我尝试过:

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

任何人都可以提出任何建议吗?

Would anyone be able to suggest anything?

推荐答案

您已将图像的绝对路径存储在数据库中,但是需要使用相对路径来引用它:

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="" />

生成的HTML必须如下所示:

The resulting HTML must look like this:

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

而不是:

<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.

这篇关于ASP.Net MVC-图Src服务器路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆