Anders
Anders

Reputation: 12570

Map path of local file ASP.NET/MVC

I have a file upload program written in ASP.NET MVC. It is currently on my local development machine, and I would like to know how (if it is possible) to generate a link for each uploaded file so when it is clicked, the item is displayed/downloaded etc.

Current code/markup that handles displaying file list:

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

I imagine I will have to change the file-handling code around once this goes live, but for now this is sufficient. Suggestions are also welcome :)

Thanks!

Upvotes: 5

Views: 14680

Answers (3)

Craig Stuntz
Craig Stuntz

Reputation: 126587

Use Url.Content, e.g.:

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

The tilde means "the root of my site, wherever that happens to be." You don't have to put your files in Content; you can put them wherever you want under your site root.

Upvotes: 12

AnthonyWJones
AnthonyWJones

Reputation: 189535

Yes the appropriate equivalent to BaseDirectory in an ASP.NET app is HttpRuntime.AppDomainAppPath. However you might also find the Server.MapPath method useful. You get to the server method via HttpContext.Current.Server.

Having said that are you sure you want this sort of code in your view. Its seems to me that the list of values you want to display ought to be generated by the controller.

Upvotes: 7

AASoft
AASoft

Reputation: 1344

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

Upvotes: 1

Related Questions