axios java springboot 前后台配合 OutputStream下载
时间: 2024-09-26 16:16:52 浏览: 60
在Spring Boot项目中,axios是一个常用的JavaScript库,用于浏览器或Node.js环境中发起HTTP请求。当需要在后台服务(Java)通过API提供文件下载功能,并通过axios驱动前端(如Vue.js)进行下载时,可以按照以下步骤操作:
1. **设置Spring API**:
在Java SpringBoot后端,创建一个处理文件下载的REST endpoint。例如:
```java
@RestController
public class FileController {
@GetMapping("/download")
ResponseEntity<StreamingResponseBody> downloadFile(@RequestParam String fileName) throws IOException {
// 从服务器路径读取文件内容
byte[] fileContent = readFromServer(fileName);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
.body(() -> new ByteArrayInputStream(fileContent));
}
private byte[] readFromServer(String fileName) throws IOException {
// 读取实际文件路径
FileInputStream fis = new FileInputStream(fileName);
try {
return new byte[fis.available()];
} finally {
fis.close();
}
}
}
```
2. **axios调用API并下载**:
在前端,你可以使用axios发起GET请求,设置 responseType 为 'blob' 或者 'arraybuffer',然后利用URL.createObjectURL() 创建下载链接,触发下载。
```javascript
axios.get('/download?fileName=<file-name>', {responseType: 'blob'})
.then(response => {
const url = window.URL.createObjectURL(response.data);
const aLink = document.createElement('a');
aLink.href = url;
aLink.download = fileName;
aLink.click(); // 触发下载
window.URL.revokeObjectURL(url); // 下载完成后释放URL资源
})
.catch(error => console.error('Download failed:', error));
```
注意替换 `<file-name>` 为实际的文件名。
阅读全文
相关推荐


















