Downloading a file from spring controllers

前端 未结 14 1180
渐次进展
渐次进展 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条回答
  •  猫巷女王i
    2020-11-22 01:35

    This code is working fine to download a file automatically from spring controller on clicking a link on jsp.

    @RequestMapping(value="/downloadLogFile")
    public void getLogFile(HttpSession session,HttpServletResponse response) throws Exception {
        try {
            String filePathToBeServed = //complete file name with path;
            File fileToDownload = new File(filePathToBeServed);
            InputStream inputStream = new FileInputStream(fileToDownload);
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename="+fileName+".txt"); 
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
            inputStream.close();
        } catch (Exception e){
            LOGGER.debug("Request could not be completed at this moment. Please try again.");
            e.printStackTrace();
        }
    
    }
    

提交回复
热议问题