spring boot vue 如何下载 文件
时间: 2024-09-30 10:06:45 浏览: 35
在Spring Boot和Vue结合的应用中,文件下载通常涉及到后端服务器返回静态资源或者通过HTTP响应头设置来完成。这里以简单的示例说明:
1. **在Spring Boot中**[^1]:
- 定义一个Controller方法,用于处理文件下载请求。
```java
@RestController
public class FileDownloadController {
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
Resource resource = new ClassPathResource(filename);
return ResponseEntity.ok()
.headers(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
.contentType(MediaType.parseMediaType(resource.getContentType()))
.body(resource);
}
}
```
这里`ClassPathResource`用于定位类路径下的文件,`HttpHeaders.CONTENT_DISPOSITION`设置了文件下载的提示。
2. **在Vue.js中**[^2]:
- 使用axios或其他HTTP客户端库发送GET请求到指定的URL(如`/download/filename.ext`)。
```javascript
export function downloadFile(filename) {
axios.get(`/download/${filename}`)
.then(response => {
const link = document.createElement('a');
link.href = response.headers['content-disposition'].split(';')[1].replace(/\"/, '');
link.download = filename;
link.click();
})
.catch(error => console.error('Error downloading file:', error));
}
```
当点击这个链接时,浏览器会自动开始下载文件。
阅读全文
相关推荐














