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以释放内存。

相关内容

热门资讯

透视计算!cloudpoker... 透视计算!cloudpoker作弊(透视)新2025教程(2024已更新)(哔哩哔哩)cloudpo...
透视好牌!aapoker免费透... 透视好牌!aapoker免费透视脚本(透视)辅助(好像是有挂)1、不需要AI权限,帮助你快速的进行a...
透视免费!poker mast... 透视免费!poker master辅助(透视)攻略方法(2023已更新)(哔哩哔哩)1、首先打开po...
透视规律!aapoker怎么控... 透视规律!aapoker怎么控制牌(透视)发牌逻辑(好像真的是有挂)aapoker怎么控制牌辅助器中...
透视插件!来玩app破解版(透... 透视插件!来玩app破解版(透视)2025版教程(2020已更新)(哔哩哔哩)1、很好的工具软件,可...
透视线上!aapoker透视脚... 透视线上!aapoker透视脚本入口(透视)透视软件(一直有挂)亲,关键说明,aapoker透视脚本...
透视好友房!拱趴大菠萝有什么挂... 透视好友房!拱趴大菠萝有什么挂(透视)解说技巧(2021已更新)(哔哩哔哩);1)拱趴大菠萝有什么挂...
透视了解!aapoker脚本(... 透视了解!aapoker脚本(透视)辅助插件工具(切实是有挂);1)aapoker脚本辅助挂:进一步...
透视ai代打!哈糖大菠萝挂(透... 透视ai代打!哈糖大菠萝挂(透视)攻略教程(2021已更新)(哔哩哔哩)1、点击下载安装,哈糖大菠萝...
透视规律!aapoker辅助器... 透视规律!aapoker辅助器怎么用(透视)真的假的(一直有挂)1、全新机制【aapoker辅助器怎...