Downloading a file from spring controllers

前端 未结 14 915
渐次进展
渐次进展 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:31

    With Spring 3.0 you can use the HttpEntity return object. If you use this, then your controller does not need a HttpServletResponse object, and therefore it is easier to test. Except this, this answer is relative equals to the one of Infeligo.

    If the return value of your pdf framework is an byte array (read the second part of my answer for other return values) :

    @RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
    public HttpEntity createPdf(
                     @PathVariable("fileName") String fileName) throws IOException {
    
        byte[] documentBody = this.pdfFramework.createPdf(filename);
    
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_PDF);
        header.set(HttpHeaders.CONTENT_DISPOSITION,
                       "attachment; filename=" + fileName.replace(" ", "_"));
        header.setContentLength(documentBody.length);
    
        return new HttpEntity(documentBody, header);
    }
    

    If the return type of your PDF Framework (documentBbody) is not already a byte array (and also no ByteArrayInputStream) then it would been wise NOT to make it a byte array first. Instead it is better to use:

    • InputStreamResource,
    • PathResource (since Spring 4.0) or
    • FileSystemResource,

    example with FileSystemResource:

    @RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
    public HttpEntity createPdf(
                     @PathVariable("fileName") String fileName) throws IOException {
    
        File document = this.pdfFramework.createPdf(filename);
    
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_PDF);
        header.set(HttpHeaders.CONTENT_DISPOSITION,
                       "attachment; filename=" + fileName.replace(" ", "_"));
        header.setContentLength(document.length());
    
        return new HttpEntity(new FileSystemResource(document),
                                      header);
    }
    

提交回复
热议问题