springboot项目中,在下载文件的时候,通过封装ResponseEntity,将文件流写入body,这种下载文件的方式,造成了下载的文件名为正文显示为下划线的形式;这个问题很好解决,直接将输入的文件名的编码格式定义成GBK格式;如下图代码;
public static ResponseEntity<FileSystemResource> export(File file) throws UnsupportedEncodingException {
if (file == null) {
return null;
}
//这个位置对文件名进行编码
String fileName = new String (file.getName().getBytes("GBK"),"ISO-8859-1");
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", "attachment; filename=" +fileName);
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new FileSystemResource(file));
}
原博客:https://blog.csdn.net/weixin_48490821/article/details/116603040