springboot使用流下载文件时文件名乱码
时间: 2023-10-26 22:27:54 浏览: 66
你可以通过设置HTTP响应的Content-Disposition头部来解决Spring Boot使用流下载文件时文件名乱码的问题。在设置头部时,需要指定filename参数,并对文件名进行URL编码。
下面是一个示例代码片段:
```java
@GetMapping("/download")
public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
// 获取文件流
InputStream fileStream = ...;
// 设置响应头部
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename=\"" +
URLEncoder.encode("文件名", "UTF-8") + "\"");
// 创建InputStreamResource对象
InputStreamResource resource = new InputStreamResource(fileStream);
// 返回响应实体
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
```
在上述代码中,你需要将"文件名"替换为你的实际文件名。使用`URLEncoder.encode`方法对文件名进行URL编码,确保特殊字符正确处理。
这样设置响应头部后,浏览器在下载文件时就能正确显示文件名,而不会乱码了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)