【SpringBoot】解决Java下载文件时文件名中的中文变成下划线的问题

中文变成下划线的问题

下图左侧是正确名称,右侧是下载之后的名称,中文变成了下划线
在这里插入图片描述

解决方式:

将字符编码转换成浏览器可以解析的字符编码 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>

下载后效果:

在这里插入图片描述

发布了610 篇原创文章 · 获赞 232 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/sinat_42483341/article/details/104229275