使用c#无法在asp.net中下载文件

时间:2016-05-10 03:33:22

标签: c# html asp.net

我在尝试制作可以从文件夹下载文件的页面时遇到问题。在页面中,我可以显示列表中的文件列表,但是当我单击下载链接时,没有任何反应,我无法下载文件。以下是我的编码:

public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }

    private void BindGrid()
    {
        if (!IsPostBack)
        {
            string[] filePaths = Directory.GetFiles(Server.MapPath("~/download"));
            List<ListItem> files = new List<ListItem>();
            foreach (string filePath in filePaths)
            {
                files.Add(new ListItem(Path.GetFileName(filePath), filePath));
            }
            GridView1.DataSource = files;
            GridView1.DataBind();
        }
    }


    protected void DownloadFile(object sender, EventArgs e)
    {
        string filePath = (sender as LinkButton).CommandArgument;
        Response.ContentType = ContentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
        Response.WriteFile(filePath);
        Response.End();
    }

 }

这是我的HTML标记:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No files uploaded">
<Columns>
    <asp:BoundField DataField="Text" HeaderText="File Name" />
    <asp:TemplateField>
        <ItemTemplate>
            <asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("Value") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

是否有任何我忽略或有任何遗漏导致我的页面无法下载文件。感谢。

2 个答案:

答案 0 :(得分:0)

您无法连接onclick事件并使其与命令参数一起使用。您需要使用Command事件。给它一个CommandName,比如&#34; DownLoadFile&#34;。因为这是在网格中,所以网格很可能会拦截命令。您将要覆盖网格RowCommand事件并捕获命令名以确定它是否是您刚刚触发的链接按钮。如果是这样,您应该能够直接从RowCommand事件参数访问CommandArgument。

答案 1 :(得分:0)

您的Asp代码相同并尝试使用此C#代码

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
    }
    private void BindGrid()
    {
     string[] filePaths = Directory.GetFiles(Server.MapPath("~/download"));
     List<ListItem> files = new List<ListItem>();
     foreach (string filePath in filePaths)
     {
        files.Add(new ListItem(Path.GetFileName(filePath), filePath));
     }
       GridView1.DataSource = files;
       GridView1.DataBind();
    }
    protected void DownloadFile(object sender, EventArgs e)
    {
        string filePath = (sender as LinkButton).CommandArgument;
        Response.ContentType = ContentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
        Response.WriteFile(filePath);
        Response.End();
    }