2017-02-13 55 views
1

我试图在ASP.NET网站上添加用于下载文件的功能。下面是保存数据的类:文件不在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上。

请帮我找出上面的代码有问题。

+0

你还没有解释你的“下载按钮”是如何与调用'Response.OutputStream.Write'的代码相关的。 – Dai

+0

您应该将代码更改为重定向到专用处理程序,该处理程序将提供该文件,而不是直接从回发事件处理程序执行。 – Dai

回答

2

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

<asp:PostBackTrigger ControlID="YourControlID" /> 
+0

谢谢...解决了这个问题... –