下载文件java spring rest api

编程入门 行业动态 更新时间:2024-10-18 18:24:22
本文介绍了下载文件java spring rest api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想制作一个rest api控制器(弹簧启动),当与get一起请求时,它将允许我下载一个excel文件.目前,我有这个端点:

i want to make a rest api controller (spring boot) that when petitioned with a get will allow me to download an excel file. currently i have this endpoint:

@RequestMapping(value = "/download.xls", method = RequestMethod.GET) public ResponseEntity Survey_Reports(@RequestParam(value = "evaluated") String evaluated){ return surveyService.getSurveysFile(evaluated); }

最终调用此方法:

public static ResponseEntity getDownloadResponse() { File file2Upload = new File("Survey_Reports.xls"); Path path = Paths.get(file2Upload.getAbsolutePath()); ByteArrayResource resource = null; try { resource = new ByteArrayResource(Files.readAllBytes(path)); } catch (IOException e) { logger.error("there was an error getting the file bytes ", e); } return ResponseEntity.ok() .contentLength(file2Upload.length()) //this line doesnt seem to work as i set the file format in the controller request mapping .contentType(MediaType.parseMediaType("application/vnd.ms-excel")) .body(resource); }

当我获得download.xls(作为映射)文件的正确性时,一切似乎都可以正常工作,但是现在我想使下载的文件具有某些特定名称,例如:ratedName.xls或userDateEndDate.xls或其他一些名称东西,有没有办法编辑响应实体来做到这一点?这样我就不必将映射命名为"download.xls"

everything seems to work semi-fine as i get the download.xls(as the mapping) file correclty, but now i want to make the downloaded file have some specific name like: evaluatedName.xls or userDateEndDate.xls or some other stuff, is there a way to edit the response entity to do so? so that i dont have to name the mapping "download.xls"

推荐答案

在 HttpServletResponse响应的上下文中,您可以这样做

In context of HttpServletResponse response you can do this like this

response.setContentType("application/csv"); response.setHeader("Content-Disposition", "attachment; filename=" + csvName);

,对于 ResponseEntity ,我假设您可以使用类似以下的内容:

and for ResponseEntity i assume you can use something like this:

ResponseEntity.ok().header("Content-Disposition","attachment; filename=" + csvName );

更多推荐

下载文件java spring rest api

本文发布于:2023-11-28 09:59:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641941.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   java   spring   rest   api

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!