使用spring boot 提供下载功能 , 当下载文件的为中文名称时, 下载本地却显示为乱码 .
需要在下载文件头处对文件名进行编码 .
public ResponseEntity<FileSystemResource> export(File file) {
if (file == null) {
return null;
}
String filename = "";
try {
filename = new String(file.getName().getBytes("UTF-8"),"iso-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
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");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new FileSystemResource(file));
}
网友评论