文件未在 ASP.NET 内下载

File does not download in ASP.NET

我正在尝试在 ASP.NET 网站上添加下载文件的功能。下面是保存数据的class:

public class L_Attachment
{
    public Int32 ParentId;
    public L_AttachmentTypes Type;
    public String FileName;
    public String FileExtension;
    public Byte[] FileData;

    public enum L_AttachmentTypes
    {
        CONTRACT = 1, 
        RECEIVE = 2
    }
}

FileData 字段包含 bytes 以构建文件。下面是我下载文件的代码。

    protected void gvAttachmentList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
    if (e.CommandName == "DownloadAttachment")
    {
    Int32 index = Convert.ToInt32(e.CommandArgument);
    Int32 id = Convert.ToInt32(this.gvAttachmentList.DataKeys[index].Value);

    L_Attachment attachment = L_Attachment.GetById(id);

    try
    {
        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=\"" + attachment.FileName + attachment.FileExtension + "\"");
        Response.AddHeader("Content-Length", attachment.FileData.Length.ToString());
        Response.BufferOutput = false;
        Response.OutputStream.Write(attachment.FileData, 0, attachment.FileData.Length);
        Response.Flush();
    }
    catch (Exception ex)
    {
        Message msg = new Message();
        msg.Type = MessageType.Error;
        msg.Msg = "Error occurred. Details: " + ex.Message;

        ShowUIMessage(msg);
    }
}

但是在用户端,当用户按下网页上的下载按钮时没有任何反应。该文件必须保存在客户端 PC 上。

请帮我找出上面代码中的错误。

您正在使用更新面板,那么您需要添加触发器。

<asp:PostBackTrigger ControlID="YourControlID" />