2009-09-16 33 views
5

我有一个用ASP.NET MVC编写的文件上传程序。它目前在我的本地开发机器上,并且我想知道如何(如果有可能)为每个上传的文件生成链接,因此当它被点击时,该项目被显示/下载等。本地文件的映射路径ASP.NET/MVC

当前代码/标记,处理显示文件列表:

<table> 
    <tr> 
     <th></th> 
     <th> 
      Name 
     </th> 
     <th> 
      Length 
     </th> 
     <th></th> 
    </tr> 
    <% 
    var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "uploads"); 
    foreach (var file in Directory.GetFiles(path)) 
    { 
     var item = new FileInfo(file); 
    %> 
    <tr> 
     <td></td> 
     <td> 
      <%=Html.Encode(Path.GetFileName(item.Name))%> 
     </td> 
     <td> 
      <%=Html.Encode(item.Length >= 1024 ? item.Length/1024 + " kilobytes" : item.Length + " bytes")%> 
     </td> 
     <td> 
      // This is the line in question. Does not work as-is. 
      <a href="<%= item.FullName %>"><%= Html.Encode(Path.GetFileName(item.Name)) %></a> 
     </td> 
    </tr> 
    <% } %> 
</table> 

我想我将不得不改变周围的文件处理代码,一旦此去住,但现在这已经足够了。建议也欢迎:)

谢谢!

回答

12

使用Url.Content,例如:

<img src="<%= Url.Content("~/Content/UserImages/FileName.jpg") %>" /> 

代字号意思是“我的地盘,只要出现这种情况是根。”您不必将文件放入内容中;你可以把它们放在你的站点根目录下的任何位置。

1
<a href="<%= Url.Content(System.Web.VirtualPathUtility.ToAppRelative("~/" + file.Substring(AppDomain.CurrentDomain.BaseDirectory.Length))) %></a> 
+0

+1正是我想要的(对于MVC3 - 链接到elmah.axd),谢谢! – ashes999 2011-12-28 21:42:11

7

是适当的相当于BaseDirectory在ASP.NET应用程序是HttpRuntime.AppDomainAppPath。但是,您也可能会发现Server.MapPath方法很有用。你通过HttpContext.Current.Server进入服务器方法。

话虽如此,你确定你想在你的视图中的这种类型的代码。在我看来,你想要显示的值列表应该由控制器生成。