服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

文件下载程序中文件名过长的问题


  今天测试文件下载程序中发现的文件名过长的问题 ,居然发现文件名编码后长度超过155就会不能正确显示和下载,最后只好找了这样一个折中的方法,截短了
  下面是那里的代码
  /// <summary>
  /// 下载附件。
  /// </summary>
  /// <param name="filename">文件名</param>
  /// <param name="path">文件路径</param>
  public static void downloadfileattachment(string filename , string path)
  {
  if (system.io.file.exists(path))
  {
  try
  {
  filename = filename.trim();
  
  for (int i = 0 ; i < system.io.path.invalidpathchars.length ; i ++)
  {
  filename = filename.trim().replace(system.io.path.invalidpathchars[i].tostring() , string.empty);
  }
  
  filename = filename.replace(system.io.path.pathseparator.tostring() , string.empty);
  
  int maxlength = 155;
  
  int length = httputility.urlencode(filename).length;
  while (length > maxlength)
  {
  int index = filename.lastindexof(".");
  if (index > 0)
  {
  filename = filename.substring(0 , index - 1) + filename.substring(index);
  }
  else
  {
  filename = filename.substring(0 , filename.length - 1);
  }
  length = httputility.urlencode(filename).length;
  }
  
  system.io.fileinfo file = new system.io.fileinfo(path);
  httpcontext.current.response.clear();
  httpcontext.current.response.appendheader("content-disposition", "attachment; filename=" + httputility.urlencode(filename));
  httpcontext.current.response.appendheader("content-length", file.length.tostring());
  httpcontext.current.response.contenttype = "application/octet-stream";
  httpcontext.current.response.writefile(file.fullname);
  httpcontext.current.response.end();
  }
  catch
  {
  }
  }
  else
  {
  httpcontext.current.response.clear();
  displaynofilemessage();
  httpcontext.current.response.end();
  }
  }

扫描关注微信公众号