Spring Boot download file (word/excel, etc.) file name Chinese garbled problem | There is no template file (templates, etc.) in the build package
Prepare the files, here I put the templates path under resources
Configure build packaged resources in pom and update maven
If the assembly packaging plug-in is used, this configuration may still not take effect. Check and configure the package.xml file.
Write a download interface and return the template file to be downloaded. fileName can be flexibly configured as needed.
@GetMapping("/download")
@ApiOperation(value = "下载导入模版", notes = "")
public void download(HttpServletResponse response) throws IOException {
String fileName = "数据项集导入模板.xlsx";
//获得待下载文件的绝对路径
String realPath = ResourceUtils.getURL("classpath:").getPath() + "templates";
//获取文件输入流
FileInputStream fileInputStream = new FileInputStream(new File(realPath, fileName));
//文件名包含中文时需要进行中文编码,否则会出现乱码问题
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
ServletOutputStream servletOutputStream = response.getOutputStream();
int len = 0;
//设置一个缓冲区,大小取决于文件内容的大小
byte[] buffer = new byte[1024];
//每次读入缓冲区的数据,直到缓冲区无数据
while ((len = fileInputStream.read(buffer)) != -1) {
//输出缓冲区的数据
servletOutputStream.write(buffer, 0, len);
}
servletOutputStream.close();
fileInputStream.close();
}
After doing this, when using swagger to test the interface, there is a high probability that the format "%A8%A1%E6%9D%BF.xlsx" will appear. This is because Swagger URL-encodes the file name, causing the file name to change when downloading. Displayed in encoded form.
Use the browser directly to get the test interface, the file encoding is normal, perfect!