spring boot+vue 文件下载
时间: 2023-05-16 17:06:36 浏览: 67
可以使用axios库来实现文件下载,具体步骤如下:
1. 在前端使用axios发送请求,获取文件的二进制数据。
```javascript
axios({
url: '/download',
method: 'get',
responseType: 'blob'
}).then(res => {
const blob = new Blob([res.data])
const fileName = 'example.pdf'
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName)
} else {
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
window.URL.revokeObjectURL(link.href)
}
})
```
2. 在后端使用Spring Boot编写下载接口,将文件的二进制数据返回给前端。
```java
@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile() throws IOException {
File file = new File("example.pdf");
byte[] bytes = FileUtils.readFileToByteArray(file);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", file.getName());
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}
```
注意:需要在后端设置响应头Content-Disposition为attachment,这样浏览器才会提示用户下载文件,而不是直接在浏览器中打开。