vue 接收ResponseEntity<byte[]> 形成下载功能
时间: 2024-05-02 21:19:41 浏览: 174
好的,关于你的问题,你可以使用以下代码实现:
前端代码:
```vue
<template>
<button class="btn" @click="downloadFile()">下载文件</button>
</template>
<script>
export default {
name: 'DownloadButton',
props: {
downloadUrl: {
type: String,
required: true
}
},
methods: {
downloadFile() {
const requestOptions = {
method: 'GET',
responseType: 'blob' // 设置返回类型为blob
};
axios
.get(this.downloadUrl, requestOptions)
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf'); // 下载文件名,根据实际情况修改
document.body.appendChild(link);
link.click();
})
.catch(error => {
console.error(error);
});
}
}
};
</script>
```
后端代码:
```java
@GetMapping(value = "/download")
public ResponseEntity<byte[]> downloadFile() throws IOException {
File file = new File("/path/to/file.pdf"); // 文件路径,根据实际情况修改
byte[] fileContent = Files.readAllBytes(file.toPath());
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.pdf"); // 下载文件名,根据实际情况修改
return ResponseEntity.ok().headers(headers).body(fileContent);
}
```
这样点击“下载文件”按钮时,浏览器会下载该文件。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)