日期:2014-05-17  浏览次数:20512 次

ASP.NET2.0做文件下载时文件下载后中文文件名显示乱码
在做上传的时候已经将文件名及路径存储好了,分别为resource_name和resource_filename.现在下载已经可以实现,英文的文件名也可以正确显示,但带中文的文件名显示为乱码,我上网找了不少资料,不过还是未能解决.下面是相关的代码,恳请高手指点...小弟感激不尽!
  //定义"下载"按钮的HTML代码
 <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%#Eval("id")%>' OnCommand="Download" Width="53px">下载</asp:LinkButton>
  
  //点击按钮后触发的事件Download及它调用的方法ResponseFile代码:
  protected void Download(object sender,CommandEventArgs e)
  {
  try
  {
  String resource_id = ((LinkButton)sender).CommandArgument.ToString();
  SqlConnection weida = new SqlConnection(ConfigurationManager.AppSettings["dbconnectionString"]);
  weida.Open();
  string str = "SELECT * FROM Resource WHERE id = '" + resource_id + "'";
  SqlCommand bind = new SqlCommand(str, weida);
  SqlDataReader datareader = bind.ExecuteReader();
  datareader.Read();
  string name = datareader["resource_name"].ToString();
  string fullname = datareader["resource_filename"].ToString();
  weida.Close();
  datareader.Close();
  Page.Response.Clear();
  string fullpath = Server.MapPath(fullname);
  bool success = ResponseFile(Page.Request, Page.Response, name, fullpath, 1024000);

  if (!success)
  Response.Write("下载文件出错!");

  Page.Response.End();
  }
  catch (Exception)
  {
  Response.Write("<script language='javascript'>alert('下载文件发生异常,请重新登录再尝试');</script>");
  }
  }
  public bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
  {
  try
  {
  FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  BinaryReader br = new BinaryReader(myFile);
  try
  {
  _Response.AddHeader("Accept-Ranges", "bytes");
  _Response.Buffer = false;
  long fileLength = myFile.Length;
  long startBytes = 0;

  int pack = 10240; //10K bytes  
  //int sleep = 200; //每秒5次 即5*10K bytes每秒  
  int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
  if (_Request.Headers["Range"] != null)
  {
  _Response.StatusCode = 206;
  string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
  startBytes = Convert.ToInt64(range[1]);
  }
  _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
  if (startBytes != 0)
  {
  _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
  }
  _Response.AddHeader("Connection", "Keep-Alive");
  _Response.ContentType = "application/octet-stream;charset=gb2312";