Downloading Files from server using Gridview [Resolved]

Posted by Nkkppp under ASP.NET on 9/3/2012 | Points: 10 | Views : 3890 | Status : [Member] | Replies : 1
Below is my html Content

<form id="form1" runat="server">
<asp:FileUpload ID="ful" runat="server" />&nbsp; <asp:Button ID="btnupload" runat="server" Text="Upload" onclick="btnupload_Click" /><br />
<asp:Label ID="lblmsg" runat="server" Visible="false" Font-Bold="true" ForeColor="CadetBlue"> </asp:Label><br />
<asp:Button ID="btnshow" runat="server" Text="ShowAllFiles"
onclick="btnshow_Click" /><br /><br /> <asp:GridView ID="gv" runat="server" AutoGenerateColumns="false" GridLines="Horizontal" AlternatingRowStyle-BackColor="DarkViolet" DataKeyNames="DocId" onrowcommand="gv_RowCommand">
<Columns> <asp:BoundField HeaderText="DocId" DataField="DocId"/> <asp:BoundField HeaderText="DocumentName" DataField="DocName" />
<asp:TemplateField> <ItemTemplate> <asp:ImageButton ID="img" runat="server" ImageUrl='<%#Eval("ImageUrl") %>' CommandName="Download" CommandArgument='<%#Eval("DocId") %>' /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div>

Below is my code for Rowcommand event i.e. when i click on the Imagebutton

protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
string filename = string.Empty;
int id = Convert.ToInt32(e.CommandArgument);
cmd = new SqlCommand("SELECT DocName,DocType FROM Documents WHERE DocID = " + id, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
filename = dr["DocName"].ToString();
Response.ContentType = dr["DocType"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
Response.TransmitFile(Server.MapPath("~/Docs/" + filename));
Initially the data is saved into database and then retrieved in Gridview.Only one problem I have noticed with my code is...when the filename contains spaces in between for eg: Dot Net.jpg (or) A B.doc & when i click on imagebutton,in the windows download popup the name is only Dot(or) A (Net.jpg,B.doc is not appearing) and when i try to save the file it is saved with no extension how to solve this.

Thank you.


Posted by: Nkkppp on: 9/3/2012 [Member] Starter | Points: 25


Guys I found the solution.

Tq all for spending time on this.

Server is considering the filename only till firstspace and the rest is ignored so done minor changes to code

Response.AddHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");

Nkkppp, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response