2011-03-28 191 views
1

当我访问我的ashx时,例如download.ashx?id = 18它获取文件,但当保存对话框弹出时,它希望我保存download.ashx而不是我存储的文件在数据库中(让我们说mypdf.pdf)如果你打开文件下载它在Visual Studio中打开,并没有真正显示任何有用的东西。是什么原因导致这种情况,我在很多浏览器和许多机器上都试过了,它们都一样吗?ASHX文件下载损坏的文件

感谢

 string id = ctx.Request.QueryString["id"]; 
     string name = null; 
     string mime = null; 

     SqlConnection con = new SqlConnection(CONN); 
     SqlCommand cmd = new SqlCommand("DownloadActivityFile", con); 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Parameters.AddWithValue("@aid", id); 

     byte[] afile = null; 
     try 
     { 
      con.Open(); 
      SqlDataReader reader = cmd.ExecuteReader(); 

      while (reader.Read()) 
      { 
       mime = reader["ActivityFileMIME"].ToString(); 
       ctx.Response.ContentType = mime; 
       afile = (byte[])reader["ActivityFile"]; 
       name = reader["ActivityFileName"].ToString(); 
      } 
      ctx.Response.Buffer = false; 
      ctx.Response.ContentType = mime; 
      ctx.Response.AddHeader("content-disposition", string.Format("attachment; {0}", name)); 
      ctx.Response.Clear(); 
      ctx.Response.BinaryWrite(afile); 
      ctx.Response.End(); 
     } 
     catch (Exception e) 
     { 
      ctx.Response.Write(e.ToString()); 
     } 
     finally 
     { 
      con.Close(); 
     } 

回答

4

您需要设置Content-Disposition: attachment; filename=\"{0}\"头。
注意,以及名称周围的引号。

+0

引号是可选的,看来;甚至[rfc](http://www.ietf.org/rfc/rfc2183.txt)都有一些例子,例如:Content-Disposition:attachment;文件名= genome.jpeg; 修改日期=“星期三,1997年2月12日16:29:51 -0500”;' – 2011-03-28 18:19:48

+0

@Marc:直到你把一个空格在文件名。 http://kb.mozillazine.org/Filenames_with_spaces_are_truncated_upon_download – SLaks 2011-03-28 18:20:42