Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stream large HTTP response in spring

We have a HTTP request which when handled in server will create a response approximately 3GB in size, this data is an aggregation of 6 queries to database, how can we send this data as individual responses of 6 queries than as an aggregation.

like image 863
venkat g Avatar asked Dec 18 '17 12:12

venkat g


2 Answers

StreamingResponseBody is used for asynchronous request processing where the application can write directly to the response OutputStream.

Checkout this article

http://www.logicbig.com/how-to/code-snippets/jcode-spring-mvc-streamingresponsebody/

http://shazsterblog.blogspot.in/2016/02/asynchronous-streaming-request.html

like image 73
Ganesh Kumbhashi Avatar answered Oct 31 '22 06:10

Ganesh Kumbhashi


I did this :

 @GetMapping("/{fileName:[0-9A-z]+}")
    @ResponseBody
    public ResponseEntity<InputStreamResource> get_File(@PathVariable String fileName) throws IOException {
        Files dbFile = fileRepository.findByUUID(fileName);

        if (dbFile.equals(null))
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);

        String filename = dbFile.getFileName();
        Resource file = storageService.loadAsResource(dbFile.getFileName());


        long len = 0;
        try {
            len = file.contentLength();
        } catch (IOException e) {
            e.printStackTrace();
        }


        MediaType mediaType = MediaType.valueOf(FileTypeMap.getDefaultFileTypeMap().getContentType(file.getFile()));

        if (filename.toLowerCase().endsWith("mp4") || filename.toLowerCase().endsWith("mp3") ||
                filename.toLowerCase().endsWith("3gp") || filename.toLowerCase().endsWith("mpeg") ||
                filename.toLowerCase().endsWith("mpeg4"))
            mediaType = MediaType.parseMediaType("application/octet-stream");


        InputStreamResource resource = new InputStreamResource(new FileInputStream(file.getFile()));

        return ResponseEntity.ok()
                .contentType(mediaType)
                .contentLength(len)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
                .body(resource);
    }
like image 37
iman Avatar answered Oct 31 '22 04:10

iman