获取response中的filename
时间: 2024-03-11 08:51:17 浏览: 19
获取`response`中的文件名需要在服务端设置`Content-Disposition`响应头。`Content-Disposition`头用于指示对于请求的内容该如何显示,以及是否允许用户下载。通常,文件下载时需要设置该头部信息,用来告诉浏览器该文件的文件名以及下载时的行为。示例如下:
```java
String fileName = "example.xlsx"; // 文件名
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
```
在前端代码中,可以通过`XMLHttpRequest.getResponseHeader()`方法获取响应头中的文件名。示例如下:
```javascript
var xhr = new XMLHttpRequest();
xhr.open('GET', '/download/example.xlsx', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
var contentDisposition = xhr.getResponseHeader('Content-Disposition');
var fileName = contentDisposition.split(';')[1].split('=')[1].trim().replace(/"/g, '');
var blob = new Blob([this.response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
xhr.send();
```
在上述示例中,我们先通过`xhr.getResponseHeader('Content-Disposition')`方法获取响应头中的`Content-Disposition`信息。接着,我们根据该信息提取文件名,然后使用该文件名设置下载链接的`download`属性。最后,我们创建了一个`Blob`对象,通过`window.URL.createObjectURL()`方法在客户端创建了一个可下载的链接,用户点击该链接即可下载文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](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)