Downloading a file from spring controllers

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

    The following solution work for me

        @RequestMapping(value="/download")
        public void getLogFile(HttpSession session,HttpServletResponse response) throws Exception {
            try {
    
                String fileName="archivo demo.pdf";
                String filePathToBeServed = "C:\\software\\Tomcat 7.0\\tmpFiles\\";
                File fileToDownload = new File(filePathToBeServed+fileName);
    
                InputStream inputStream = new FileInputStream(fileToDownload);
                response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment; filename="+fileName); 
                IOUtils.copy(inputStream, response.getOutputStream());
                response.flushBuffer();
                inputStream.close();
            } catch (Exception exception){
                System.out.println(exception.getMessage());
            }
    
        }
    

提交回复
热议问题