Spring构建CSV字符串并用它下载文件

我想要的是当我访问/getcsv下载一个csv file


@RequestMapping(value = "/getcsv", method = RequestMethod.GET)

public void getCSV(HttpServletResponse response){


    String csv = "a,b";


    response.setContentType("text/csv");


    //what to do now?


}

我不知道如何激发csv file包含我的字符串的下载。


海绵宝宝撒
浏览 94回答 2
2回答

临摹微笑

您可以在响应的输出流中写入数据。    @RequestMapping(value = "/getcsv", method = RequestMethod.GET)    public void getCSV(HttpServletResponse response){        String csv = "a,b";        response.setContentType("application/octet-stream");        response.setHeader("Content-Disposition", "fileName.csv");        response.setHeader("Access-Control-Expose-Headers","Authorization, Content-Disposition");        try (PrintWriter pw = new PrintWriter(response.getOutputStream())) {            pw.write(csv);        }    }

弑天下

您可以尝试以下代码。@PostMapping(value = "/getcsv", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)&nbsp; public ResponseEntity<?> downloadFile(@RequestParam("fileName") String fileName) {&nbsp; &nbsp; String dirPath = "E:/some-directory-path/";&nbsp; &nbsp; byte[] fileBytes = null;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; fileBytes = Files.readAllBytes(Paths.get(dirPath + fileName));&nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }&nbsp; &nbsp; return ResponseEntity.ok()&nbsp; &nbsp; &nbsp; &nbsp; .contentType(MediaType.APPLICATION_OCTET_STREAM)&nbsp; &nbsp; &nbsp; &nbsp; .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")&nbsp; &nbsp; &nbsp; &nbsp; .body(fileBytes);&nbsp; }您必须设置为 Application Octet Stream 才能下载任何文件。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java