Home > OS >  Does Spring ResponseEntity load the full data from a Resource into Memory?
Does Spring ResponseEntity load the full data from a Resource into Memory?

Time:03-24

I'm writing a method that needs to return PDF files from another Webserver:

    @RequestMapping(value = "download", method = RequestMethod.GET)
    public ResponseEntity<Resource> download(String document) throws Exception {
        
        String file = "http://blabla.com?document="   document;
        HttpHeaders headers = new HttpHeaders();

        headers.add("content-disposition", "attachment; filename="   document);
        headers.setContentType(MediaType.APPLICATION_PDF);
        
        UrlResource u = new UrlResource(new URL(file));
        return ResponseEntity.ok().headers(headers).body(u);
    }

This seems to work. The PDFs can get quite big however, and Im not entirely sure how ResponseEntity.body() reads and writes the file.

Is the full data being read into memory here? If so, how do I manage to make it stream it instead?

I know how to do it using HttpServletResponse and writing to outputstream, but I was wondering if Spring already takes care of this here.

CodePudding user response:

Spring takes care of this for you. A Resource response is streamed to the client by reading from the resource's input stream and writing to the response's output stream. If you'd like to look at the code, this is done in ResourceHttpMessageConverter.

  • Related