ASP.. NET下载脚本正在加载当前页面文件作为下载文件

本文关键字:文件 下载 当前页 NET 脚本 ASP 加载 | 更新日期: 2023-09-27 18:08:18

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

ASP.. NET下载脚本正在加载当前页面文件作为下载文件

试试这个:

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