文件无法在ASP.NET中下载

时间:2017-02-13 09:36:35

标签: asp.net .net-3.5

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

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

请帮我查一下上面代码中的错误。

1 个答案:

答案 0 :(得分:2)

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

<asp:PostBackTrigger ControlID="YourControlID" />