Spring构建CSV字符串并下载一个文件

时间:2019-07-16 13:57:07

标签: java spring

我想要的是访问/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的下载。

2 个答案:

答案 0 :(得分:1)

您可以在响应的outputStream中写入数据。

    @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);
        }
    }

答案 1 :(得分:0)

您可以尝试以下代码。

@PostMapping(value = "/getcsv", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
  public ResponseEntity<?> downloadFile(@RequestParam("fileName") String fileName) {
    String dirPath = "E:/some-directory-path/";
    byte[] fileBytes = null;
    try {
      fileBytes = Files.readAllBytes(Paths.get(dirPath + fileName));
    } catch (IOException e) {
      e.printStackTrace();
    }
    return ResponseEntity.ok()
        .contentType(MediaType.APPLICATION_OCTET_STREAM)
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
        .body(fileBytes);
  }

您必须设置为Application Octet Stream才能下载任何文件。