java下载功能vue实现
Java 后端文件下载功能实现
后端需提供文件下载的接口,通常使用 HttpServletResponse 实现。以下是一个简单的 Java Spring Boot 示例:
@GetMapping("/download")
public void downloadFile(HttpServletResponse response) throws IOException {
// 文件路径(示例)
File file = new File("/path/to/file.pdf");
// 设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
response.setContentLength((int) file.length());
// 写入输出流
try (InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
}
}
Vue 前端调用下载接口
前端通过 axios 或其他 HTTP 库调用后端接口,处理文件下载。以下是 Vue 的实现方法:
// 方法一:直接通过 window.open 或 a 标签触发下载
downloadFile() {
window.open('http://your-api-url/download', '_blank');
}
// 方法二:使用 axios 处理二进制流(推荐)
downloadFile() {
axios({
url: 'http://your-api-url/download',
method: 'GET',
responseType: 'blob' // 关键:指定响应类型为 blob
}).then(response => {
// 创建下载链接
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'filename.pdf'); // 设置文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link); // 移除临时元素
});
}
处理大文件下载进度
如果需要显示下载进度,可以通过 axios 的 onDownloadProgress 实现:
axios({
url: 'http://your-api-url/download',
method: 'GET',
responseType: 'blob',
onDownloadProgress: progressEvent => {
const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(`下载进度: ${percent}%`);
}
}).then(response => {
// 处理文件下载
});
跨域问题处理
如果遇到跨域问题,需在后端配置 CORS。Spring Boot 的配置示例:
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true);
}
}
文件下载安全增强
为增强安全性,可以在后端对文件名进行校验或加密:
// 校验文件名防止路径遍历攻击
String safeFileName = file.getName().replaceAll("[^a-zA-Z0-9.-]", "_");
response.setHeader("Content-Disposition", "attachment; filename=" + safeFileName);
以上方法结合了 Java 后端和 Vue 前端的实现,可根据实际需求调整细节。







