Apache 의 IOUtils 를 사용 하여 파일 다운 로드 를 실현 합 니 다.

쓸데없는 말 은 하지 않 고 코드 를 직접 올 리 고 주석 도 비교적 분명하게 썼 다.
/**
     *       
     * @param filename              , /template/userTemplate.xls
     */
    @RequestMapping("/common/downloadtemplatefile")
    public void downloadTemplateFile(String filename, HttpServletResponse response,
                                     HttpServletRequest request) {
        LOGGER.info("【      】filename : " + filename);
        if (StringUtils.isNotBlank(filename)) {
            LOGGER.warn("【        】");
            throw new RuntimeException("        ");
        }
        //      
        int lastIndexOfPoint = filename.lastIndexOf(".");
        String suffix = filename.substring(lastIndexOfPoint);
        //        
        String filepath = request.getSession().getServletContext().getRealPath(filename);
        File myfile = new File(filepath);
        //   response
        response.reset();
        //   response Header
        response.addHeader("Content-Disposition", "attachment;filename=" + filename.getBytes()
                                                  + suffix);
        response.addHeader("Content-Length", "" + myfile.length());
        response.setContentType("application/octet-stream");

        OutputStream toClient = null;
        InputStream fis = null;
        //          servlet   
        try {
            toClient = new BufferedOutputStream(response.getOutputStream());
            fis = new BufferedInputStream(new FileInputStream(myfile));
            //  ioutil        ,      
            IOUtils.copy(fis, toClient);
            toClient.flush();
        } catch (Exception e) {
            LOGGER.error("【      】", e);
            throw new RuntimeException("      ");
        } finally {
            //   
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(toClient);
        }

    }

좋은 웹페이지 즐겨찾기