中文变成下划线的问题
下图左侧是正确名称,右侧是下载之后的名称,中文变成了下划线
解决方式:
将字符编码转换成浏览器可以解析的字符编码 ISO8859-1
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"),"ISO8859-1"));
代码示例
FileController.java
/**
* 文件下载
*/
@PostMapping("/download")
public void download(String filename, HttpServletResponse res, HttpServletRequest req) throws IOException {
res.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "ISO8859-1"));
ServletOutputStream os = res.getOutputStream();
String path = uploadPath;
System.out.println("In FilesController, path = " + path);
System.out.println("In FilesController, filename = " + filename);
File file = new File(path, filename);
os.write(FileUtils.readFileToByteArray(file));
os.flush();
os.close();
}
downloadfile.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>文件下载</p>
<form action="download" method="POST" enctype="multipart/form-data">
文件名称:
<input type="text" name="filename"/>
<input type="submit" value="下载"/>
</form>
<hr/>
</body>
</html>