J2EE download file name Chinese garbled problem

When downloading files in JAVA WEB APP, when it contains Chinese names, it will cause garbled characters in different browsers and different operating systems;

Tried the following methods, to no avail .

        String name = fileName + ".xlsx";
        if (httpServletRequest.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            name = URLEncoder.encode(name, "GBK");
        } else {
            name = new String(name.getBytes("GBK"), "ISO8859-1");
        }

        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + name);

Finally found an effective method on StackOverflow; tested in MAC, Windows, IE, Chrome, FF;

final String encodedFileName = encodeFilename(fileNameToEncode); 
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

private String encodeFilename(final String filename)
{
  try{        
    URI uri = new URI(null, null, filename, null);      
    String encodedName = uri.toASCIIString(); 
    return encodedName;
  }
  catch(URISyntaxException ex){
      return filename;
  }
}

from: http://stackoverflow.com/questions/22319277/how-to-set-chinese-filename-correctly-for-different-browsers-when-download-file

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325737258&siteId=291194637