Java后端+Angular前端REST接口实现浏览器zip下载方案咨询
最简实现方案
1. Java后端修改
1.1 调整打包方法返回值
把原来的void返回改为返回生成的zip文件对象,方便后续读取流:
public File getDownloadZip(String[] files, String folderName) throws IOException { // 原有打包逻辑不变 ZipUtil.pack(new File("Download"), new File("selected-files.zip")); return new File("selected-files.zip"); }
1.2 补全HttpHandler返回逻辑
在调用完打包方法后,设置下载响应头,把文件流写入响应,完成后删除服务端文件:
server.createContext("/files/downloadZip", new HttpHandler() { @Override public void handle(HttpExchange exchange) throws IOException { if (!handleTokenPreflight(exchange)) { return; } // 原有参数解析逻辑不变 // ... // 调用打包方法获取生成的zip文件 File zipFile = Controller.getDownloadZip(files, folderName); try { // 设置响应头 exchange.getResponseHeaders().set("Content-Type", "application/zip"); exchange.getResponseHeaders().set("Content-Disposition", "attachment; filename=\"selected-files.zip\""); exchange.sendResponseHeaders(200, zipFile.length()); // 把zip文件流写入响应 Files.copy(zipFile.toPath(), exchange.getResponseBody()); exchange.getResponseBody().flush(); } finally { // 关闭响应流 exchange.getResponseBody().close(); // 下载完成后删除服务端临时文件 zipFile.delete(); // 可选:删除临时Download文件夹 deleteDir(new File("Download")); } return; } }); // 补充删除文件夹的工具方法 private void deleteDir(File dir) { File[] files = dir.listFiles(); if (files != null) { for (File file : files) { deleteDir(file); } } dir.delete(); }
2. Angular前端修改
2.1 调整请求方法,指定返回类型为blob
// 修改返回类型为Observable<Blob>,添加responseType配置 httpGetDownloadZip(target: string[]): Observable<Blob> { const params = new HttpParams().set('target', String(target)).set('numberOfFiles', String(target.length)); const headers = new HttpHeaders().set('token', this.tokenService.getStorageToken()); const options = { headers, params, responseType: 'blob' as const // 关键:指定返回类型为二进制流 }; return this.http .get<Blob>(this.BASE_URL + '/files/downloadZip', options) .pipe(catchError(this.handleError<Blob>('httpGetZip'))); }
2.2 调用方法时触发浏览器下载
在触发下载的点击事件逻辑里订阅请求,拿到blob后生成下载链接:
downloadZip() { // 替换为你的选中文件列表变量 const target = this.selectedFileList; this.httpGetDownloadZip(target).subscribe(blob => { // 创建临时下载链接 const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'selected-files.zip'; a.click(); // 释放浏览器资源 window.URL.revokeObjectURL(url); }); }
内容的提问来源于stack exchange,提问作者Kass224
相关产品推荐
相关产品推荐

