Fix Garbled Filename in Java
When downloading files in Java, there may be situations where the file name appears in a garbled form, which is usually caused by encoding issues. The solution is as follows:
- Set the encoding format of the downloaded file name to UTF-8.
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
- Use the FilenameUtils class from the Apache Commons IO library to handle file name encoding.
String encodedFileName = FilenameUtils.encodeFileName(request, fileName);
response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
- Set the file name encoding using the setHeader method in the javax.servlet.http.HttpServletResponse class.
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
By using the above methods, the issue of garbled file names when downloading Java files can be resolved, ensuring that the downloaded file names are displayed correctly.