[c#]ASP.NET 下载脚本加载当前页面文件的下载文件

标签: Asp.net C#
发布时间: 2017/2/25 3:20:39
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

从我的数据库下载的文件在 ASP.NET 中创建脚本。当我点击下载按钮时,下载加载的文件是标题与页我下载按钮的名称和文件保存为.aspx 文件而不是.docx,最初保存它时我把它上传。

请我需要你的帮助来获得此解决。

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 "";
    }
}

解决方法 1:

试试这个︰

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

标头名称是 Content-Disposition ,不 content-deposition

赞助商