Downloading a file from spring controllers

前端 未结 14 913
渐次进展
渐次进展 2020-11-22 01:06

I have a requirement where I need to download a PDF from the website. The PDF needs to be generated within the code, which I thought would be a combination of freemarker and

14条回答
  •  臣服心动
    2020-11-22 01:46

    Below code worked for me to generate and download a text file.

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity getDownloadData() throws Exception {
    
        String regData = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
        byte[] output = regData.getBytes();
    
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("charset", "utf-8");
        responseHeaders.setContentType(MediaType.valueOf("text/html"));
        responseHeaders.setContentLength(output.length);
        responseHeaders.set("Content-disposition", "attachment; filename=filename.txt");
    
        return new ResponseEntity(output, responseHeaders, HttpStatus.OK);
    }
    

提交回复
热议问题