2010-06-17 30 views
2

我需要在ASP.NET MVC页面上显示将存储在服务器上的图像 我有一个应用程序类,可以用来提供路径为存储在服务器上的映像提供路径,而不是在应用程序文件中

这样

public static class AppHelper 
{ 
    public static string ImageLowResPath(string imageName) 
    { 

     } 
} 

我怎样才能获得存储在C文件路径:这里的服务器的驱动?

在我看来,我会得到的文件路径这样

IMG SRC = '<%= AppHelper.ImagelowResPath( “10-1010.jpg”)%>'

谢谢

回答

2

你必须创建一个返回FileStreamResult如果动作该文件在您的wwwroot之外。

例如。

public FilestreamResult GetPicture(string Filename) { 
     Filename = @"C:\SomePath\" + Filename; 
      return new FileStreamResult(new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read), "image/jpeg")); 
    } 

你的HTML现在看起来应该是这样

<img src="/Controller/GetPicture?Filename=test.jpg" /> 

更新 只要你的图片是不经常改变的静态内容和你没有需要实施某种形式的访问控制这确实不是最好的解决方案。

根据最佳实践,您应该将组件跨多个域分割。雅虎发布了关于加速网站的最佳实践的优秀指南 http://developer.yahoo.com/performance/rules.html#split

+0

哦,我的朋友谢谢!完美地工作。我开始做类似的事情,但试图返回它作为一个字节[]我不知道FileStreamResult。这让生活变得如此简单。 谢谢! – twal 2010-06-17 16:18:43

+0

现在我想知道我正在做的最佳做法。我不想将所有图像保存在我的应用程序中,因为包含图像的文件夹被我的一些其他应用程序用于读取和写入。 有没有更好的方式获取和上传这些图像像使用虚拟目录(虽然我真的不知道如何做到这一点)或什么? – twal 2010-06-20 20:45:19

+0

@ marc.d你介意看看我的问题引用你的答案[这里](http://stackoverflow.com/q/26768021/1751090)? – Rachael 2014-11-05 22:57:41

0

您需要使用使用Server.Mappath(...),这将虚拟路径映射到它的物理位置在磁盘上:

string path = "~/Images/10-1010.jpg"; 
string filePath = Server.MapPath(path); 
+0

图像不会在应用程序中保存。就在服务器文件系统上,因为它们将被添加到应用程序之外。这仍然会找到他们吗?它们不在www的根目录 – twal 2010-06-17 15:25:06

+0

不,它不会找到图像,除非它们映射到另一个虚拟目录。 – SWeko 2010-06-17 15:37:57

+0

好吧,我不这么认为,有没有办法将它们从服务器文件系统中取出? – twal 2010-06-17 15:40:46

0

呃,我不知道你在问什么的,但你可以尝试即时通讯个人,然后访问服务器共享?

[DllImport("advapi32.dll",EntryPoint = "LogonUser", SetLastError = true)] 
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, 
     int dwLogonType, int dwLogonProvider, ref IntPtr phToken); 

IntPtr admin_token = IntPtr.Zero; 
WindowsIdentity wid = WindowsIdentity.GetCurrent(); 
WindowsIdentity wid_admin; 
WindowsImpersonationContext wic; 

LogonUser(user, servername, pass, 9, 0, ref admin_token) 
wid_admin = new WindowsIdentity(admin_token); 
wic = wid_admin.Impersonate(); 

一旦你冒充有人用适当priveleges你可以去

\\服务器\ C $ \(图像路径)

+0

哦,我的坏,你正在寻找文件路径,而不是访问该文件。 – FlyingStreudel 2010-06-17 15:52:42

相关问题