Angular前端Spring后端文件下载不起作用或损坏。
创始人
2024-10-29 02:00:45
0

在Spring后端中,可以使用以下代码来实现文件下载:

@GetMapping("/download/{fileName}") public ResponseEntity downloadFile(@PathVariable String fileName) throws IOException { File file = new File(fileName); ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(file.toPath())); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName()) .contentLength(file.length()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(resource); }

在Angular前端中,可以使用以下代码来下载文件:

downloadFile(fileName: string) { this.http.get('http://localhost:8080/api/download/' + fileName, { responseType: 'blob' }) .subscribe(res => { const a = document.createElement('a'); const objectUrl = URL.createObjectURL(res); a.href = objectUrl; a.download = fileName; a.click(); URL.revokeObjectURL(objectUrl); }); }

这个代码片段使用Angular的HttpClient来发出GET请求以获取文件,并使用Blob作为响应类型,以便在URL.createObjectURL中使用它。downloadFile方法中创建一个a元素,并将其属性设置为用于下载文件的objectUrl。最后,a元素的click()方法被调用以下载文件,文件下载后需要销毁objectUrl以释放内存。

相关内容

热门资讯

透视辅助!hhpoker有没有... 透视辅助!hhpoker有没有透视辅助(透视)werplan脚本,教程策略(竟然有挂)-哔哩哔哩1、...
透视教你!wepoker模拟器... 您好,wepoker到底有没有透视这款游戏可以开挂的,确实是有挂的,需要了解加去威信【4852750...
透视透视!wepoker怎么开... 透视透视!wepoker怎么开辅助(透视)佛手大菠萝13道挂哪里,教程攻略(真是有挂)-哔哩哔哩1、...
透视透视!hhpoker真的有... 透视透视!hhpoker真的有透视吗(透视)pokermaster破解版,教程策略(确实有挂)-哔哩...
透视揭露!wepoker能不能... 透视揭露!wepoker能不能透视(透视)wepoker免费透视脚本,教程窍要(有挂详细)-哔哩哔哩...
透视解迷!wpk刷入池率脚本(... 透视解迷!wpk刷入池率脚本(透视)wepoker高级辅助,教程技法(真的有挂)-哔哩哔哩1、玩家可...
透视推荐!wepoker亲友圈... 透视推荐!wepoker亲友圈有用吗(透视)wepoker透视有没有,教程教材(有挂详细)-哔哩哔哩...
透视分享!hhpoker智能辅... 透视分享!hhpoker智能辅助插件(透视)有没有人wepoker,教程教程书(真实有挂)-哔哩哔哩...
透视推荐!pokermaste... 透视推荐!pokermaster脚本(透视)佛手在线大菠萝技巧,教程手段(有挂规律)-哔哩哔哩1、很...
透视分享!哈糖大菠萝开挂(透视... 透视分享!哈糖大菠萝开挂(透视)wpk私人局辅助是真的吗,教程练习(有挂技术)-哔哩哔哩1、这是跨平...