2016-12-28 85 views
0

我試圖下載文件,當用戶點擊從gridview的鏈接按鈕事件,但該文件沒有下載。無法下載LinkBut​​ton事件點擊文件

的代碼,當用戶點擊LinkBut​​ton的事件我有:使用一個內存流寫入文件時

protected void downloadLink_Click1(object sender, EventArgs e) 
{ 
    LinkButton lnkbtn = sender as LinkButton; 
    GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow; 


    string filename = lnkbtn.CommandArgument; 

    byte[] mybuffer = Encoding.UTF8.GetBytes(filename); 

    Response.Clear(); 
    Response.ClearHeaders(); 
    Response.ClearContent(); 
    //this puts the response to a page 
    Response.ContentType = "application/" + "octet-stream"; 
    Response.AddHeader("Content-disposition", "attachment; filename=" + filename); 
    Response.AddHeader("Content-Length", mybuffer.Length.ToString()); 

    Response.BinaryWrite(mybuffer); 
    Response.Flush(); 
    Response.Close(); 
    Response.End(); 

}

回答

0

此代碼對我的作品。我的代碼和你的代碼之間的區別是我有一個Content-Length頭。您可能需要獲取文件大小並添加此標題。

MemoryStream mybuffer= New MemoryStream(File.ReadAllBytes(filename)); 
Response.Clear(); 
    Response.ClearHeaders(); 
    Response.ClearContent(); 
       //this puts the response to a page 
    Response.ContentType = "application/" + "octet-stream"; 
    Response.AddHeader("Content-disposition", "attachment; filename=" + filename); 
    Response.AddHeader("Content-Length", mybuffer.Length.ToString()); 

    Response.BinaryWrite(mybuffer); 
    Response.Flush(); 
    Response.Close(); 
    Response.End(); 
相關問題