Spring MVC : large files for download, OutOfMemoryException

前端 未结 2 1891
温柔的废话
温柔的废话 2020-12-05 03:22

How to provide large files for download through spring controller ? I followed few discussions on similar topic :

Downloading a file from spring controllers

相关标签:
2条回答
  • 2020-12-05 04:04

    It is because you are reading the entire file into memory, use a buffered read and write instead.

    @RequestMapping(value = "/file/{dummyparam}.pdf", method = RequestMethod.GET, produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void getFile(@PathVariable("dummyparam") String dummyparam, HttpServletResponse response) {
    
    
        InputStream is = new FileInputStream(resultFile);
    
        response.setHeader("Content-Disposition", "attachment; filename=\"dummyname " + dummyparam + ".pdf\"");
    
    
        int read=0;
        byte[] bytes = new byte[BYTES_DOWNLOAD];
        OutputStream os = response.getOutputStream();
    
        while((read = is.read(bytes))!= -1){
            os.write(bytes, 0, read);
        }
        os.flush();
        os.close(); 
    }
    
    0 讨论(0)
  • 2020-12-05 04:17

    For Spring , Need use InputStreamResource class in ResponseEntity .

    Demo Code :

            MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, fileName);
            System.out.println("fileName: " + fileName);
            System.out.println("mediaType: " + mediaType);
    
            File file = new File(DIRECTORY + "/" + fileName);
            InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
    
            return ResponseEntity.ok()
                    // Content-Disposition
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
                    // Content-Type
                    .contentType(mediaType)
                    // Contet-Length
                    .contentLength(file.length()) //
                    .body(resource);
        }
    

    Ref Link : https://o7planning.org/en/11765/spring-boot-file-download-example

    0 讨论(0)
提交回复
热议问题