简体   繁体   中英

How do I dynamically create file download links in code behind in ASP.NET?

I have files on the web server. I want to make them available for download to a client. However, I don't know what the files will be, or even how many there will be until runtime. If I create a hyperlink with the NavigateUrl set to the file location on the server, then the client just tries to locate the file on their local system at that location, so that doesn't work. I was able to get a single file to work using a linkbutton, but that is also not an option because I can't create it dynamically.

Is there a way to do this dynamically in ASP.NET?

The way I eventually solved this was to use a repeater and then put the action in the repeater instead of in the link button.

<asp:Repeater id="repLinks" runat="server" OnItemCommand="repLinks_OnItemCommand">
    <ItemTemplate>
        <li>
            <asp:LinkButton ID="HyperLink1" runat="server" Text='<%# Eval("Name") %>' CommandArgument='<%# Eval("Name") %>'>
            </asp:LinkButton>
        </li>
    </ItemTemplate>
</asp:Repeater>

And then the code behind as follows:

protected void repLinks_OnItemCommand(object sender, RepeaterCommandEventArgs e)
{
    Current.Response.AddHeader("Content-disposition", "attachment; filename=" & fileName)
    Current.Response.ContentType = "application/octet-stream"
    Current.Response.WriteFile(System.IO.Path.Combine(_path, e.CommandArgument.ToString))
    Current.Response.Flush()
    Current.Response.[End]()
}

The thing I was missing is that I could have the same handler for every LinkButton in the repeater, and then just pass the filename as a CommandArgument.

I would read the files from the server and display them in a Repeater Control

//the relative folder path
string folder = "/images";

//read all the files in the folder
DirectoryInfo di = new DirectoryInfo(Server.MapPath(folder));
FileInfo[] files = di.GetFiles().OrderBy(p => p.Name).ToArray();

//bind to a Repeater
Repeater1.DataSource = files;
Repeater1.DataBind();

And then on the aspx page

<ul>
    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>
            <li>
                <asp:HyperLink ID="HyperLink1" runat="server" 
                     NavigateUrl='<%# "/images/" + Eval("Name") %>'><%# Eval("Name") %>
                </asp:HyperLink>
            </li>
        </ItemTemplate>
    </asp:Repeater>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM