java传一个httpservletresponse,设置了header,并且里面有filename,然后前端用new blob接收后端传来的二进制文件流,再用URL.createObjectURL打开下载。但是下载的时候并没有获取到文件名,这是为什么
时间: 2024-02-18 17:04:16 浏览: 179
这可能是由于在设置HTTP响应头时,未正确设置Content-Disposition头。Content-Disposition头是用于指定如何显示响应体的附加信息。如果你想让浏览器在下载文件时显示文件名,可以将Content-Disposition头设置为attachment,并在filename参数中指定文件名。例如:
```
response.setHeader("Content-Disposition", "attachment; filename=\"myfile.txt\"");
```
请注意,filename参数值应该使用双引号括起来,并且需要避免使用特殊字符和空格。如果文件名中包含特殊字符,可以使用Java的URLEncoder对文件名进行编码,例如:
```
String encodedFilename = URLEncoder.encode("my file.txt", "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFilename + "\"");
```
在前端接收到二进制文件流后,可以使用FileSaver.js库来保存文件并设置文件名。例如:
```
import FileSaver from 'file-saver';
// fetch binary data from backend
fetch('/download')
.then(response => response.blob())
.then(blob => {
// save file with specified filename
FileSaver.saveAs(blob, 'myfile.txt');
});
```
这样就可以在下载文件时正确获取文件名。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)