日期:2014-05-18  浏览次数:20431 次

将各种类型的文件存储到sqlserver后,怎样将文件下载下来?
这是我从sql中下载文件的代码:
string connStr = ConfigurationManager.ConnectionStrings["sqlConn"].ConnectionString;
  SqlConnection myConnection = null;
  string strDownloadSql = "SELECT * FROM scanfile where id=" + fid;
  try
  {
  myConnection = new SqlConnection(connStr);
  myConnection.Open();

  SqlCommand sqlcmd = new SqlCommand(strDownloadSql, myConnection);
  SqlDataReader ddr = sqlcmd.ExecuteReader();
  if (ddr.Read())
  {
  string fileType=ddr["fileName"].ToString();
  fileType = fileType.Split('.')[1].ToString().Trim();
  Response.Write(fileType + " lxmlxmlxm " + ddr["fileName"].ToString());
  Response.ContentType = "application/"+fileType;

  Response.AddHeader("Content-Disposition", "attachment;FileName=" + HttpUtility.UrlEncode(ddr["fileName"].ToString(), System.Text.Encoding.UTF8));

  Response.BinaryWrite((byte[])ddr["fileData"]);
  Response.End();

  }

  }

弹出下载页面后,文件类型以及文件名都是乱码,而且下载后的文件也不能被识别,大家帮我想下办法,都急死了

------解决方案--------------------
你得通过流读取出来呀.存进去应该是二进制的吧.

你直接ddr["fileName"].ToString()这样取能行吗..汗~~
------解决方案--------------------
C# code
byte[] buffer = (byte[])ddr["fileData"];
Response.Expires = 0;
Response.Buffer = true;
Response.Clear();
Response.ContentType = "Application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + 
    HttpUtility.UrlEncode("文件名.扩展名", System.Text.Encoding.UTF8));
Response.AddHeader("Content-Length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
Response.Flush();
Response.End();

------解决方案--------------------
以前遇见过。很有可能是这个问题
Response.ContentType = "Application/octet-stream";
--"Application/octet-stream";