Fix Garbled Characters in Spring Boot Downloads

If there is garbled text when downloading files using Spring Boot, it may be caused by encoding issues with the file names. You can try the following methods to resolve the issue:

  1. Disposition of content
  2. HTTP headers
  3. Arrangement of content
String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
headers.add("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
  1. Type of content
  2. This refers to a file that is downloaded or transferred as a binary stream.
  3. UTF-8 character encoding is used for representing text in various languages and scripts.
headers.add("Content-Type", "application/octet-stream; charset=UTF-8");
  1. If the content of the file itself may also contain garbled characters, you can specify the character encoding in the file stream.
InputStream inputStream = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

By using these methods, we can ensure that the encoding of both the file name and file content is correct, thereby preventing garbled text issues.

bannerAds