2011-03-14 21 views
0

想象一下,有一个web(mvc)应用程序,服务器上的主目录是默认的c:\intepub\wwwroot。我需要的是:如何呈现未存储在Web应用程序主文件夹中的图像文件?

  1. 用户请求http://server/randomPicture
  2. 用一个简单的网页服务器的响应与随机图片上它从一个预定义的路径,这是 iis的文件夹/应用程序,像d:\lolcats\

当然,这个样本非常简化。我的解决办法是:当请求/randomPicture/,随机图片复制到APP_Images/current_response.jpg或任何应用程序的主文件夹,然后简单地渲染

<img src="../APP_Images/current_response.jpg" /> 

这是唯一的解决办法还是有一个更文明的方式做到这一点?

回答

3

有很多方法可以做到这一点,但最简单的方法是最简单的方法:只需在IIS中为图像位置创建一个虚拟文件夹即可。

1

如下您可以使用一个HTTP处理程序:

public class GetImage : IHttpHandler 
{ 
    public void ProcessRequest(HttpContext context) 
    { 
     DateTime now = DateTime.Now; 
     context.Response.Cache.SetExpires(now.AddYears(1)); 
     context.Response.Cache.SetCacheability(HttpCacheability.Public); 
     context.Response.Cache.SetValidUntilExpires(true); 
     context.Response.Cache.SetLastModified(now); 
     context.Response.Cache.VaryByParams["FileID"] = true; 
     context.Response.Cache.SetOmitVaryStar(true); 

     context.Response.ContentType = file.ContentType; 
     context.Response.AppendHeader("content-length", file.ContentLength.ToString()); 

     //TODO: Get your file here 
     string contentDisposition = String.Empty; 
     contentDisposition += "filename=" + file.OriginalFilename; 

     context.Response.AppendHeader("content-disposition", contentDisposition); 
     string imagePath = Path.Combine(HostingEnvironment.MapPath(Settings.Default.MediaPath), file.LocalFilename); 
     context.Response.WriteFile(imagePath); 
    } 

    public bool IsReusable 
    { 
     get 
     { 
      return false; 
     } 
    } 
} 

,并使用它像这样:

<img src="/Handlers/GetImage.ashx?FileID=' + thumbnailFileID + '" alt="" /> 
相关问题