Charly Tochukwu Charly Tochukwu - 2 months ago 14
ASP.NET (C#) Question

my asp.net download script is loading current page file as the download file

I create a script in asp.net for downloading a file from my database. When i click on the download button, the file loading for download is title with name of the page my download button is and the file is saved as a .aspx file instead of a .docx as it was originally saved when i uploaded it.

Please i need your assistance to get this solve. Thank you

protected void Download(object sender, EventArgs e)
{
if(Request.QueryString["Request-Id"] != "")
{
string fileName = getFileName(Convert.ToInt32(Request.QueryString["Request-Id"]));
if(fileName != "") {
Response.ContentType = "Application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AppendHeader("content-deposition", "attachment/filename=\""+fileName+"\"");
Response.TransmitFile(Server.MapPath("/Uploads/" + fileName));
Response.End();
}
}
}

protected string getFileName(int id)
{
string connStr = ConfigurationManager.ConnectionStrings["DbCall"].ToString();
SqlConnection conn = new SqlConnection(connStr);

conn.Open();
SqlCommand command = new SqlCommand("select Conveyance_Document from Convey where Request_Id = @Id", conn);
command.Parameters.AddWithValue("@Id", Convert.ToInt32(id));

SqlDataReader sdr = command.ExecuteReader();

if (sdr.Read())
{
string fileName = sdr["Conveyance_Document"].ToString();
conn.Close();
conn.Dispose();
return fileName;
}
else
{
conn.Close();
conn.Dispose();
return "";
}
}

Answer

Try this:

Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";  
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(Server.MapPath("/Uploads/" + fileName));
Response.End();

The header name is Content-Disposition, not content-deposition.