springbootjar 실행 시 파일 다운로드

2005 단어
  @RequestMapping(value = "/excel", method = RequestMethod.GET)
    public void download(HttpServletRequest request, HttpServletResponse response,
                         @RequestParam(value = "filename") String filename) throws Exception{
        logger.debug(" :filename=" + filename);
        InputStream stream = getClass().getClassLoader().getResourceAsStream("templates"+File.separator+filename);
//        if (filename.contains("Template")) {
//            path = request.getServletContext().getRealPath("file/template/");
//        } else {
//            path = ExcelUtil.errorfilePath;
//        }

        if (stream==null) {
            throw new BizException("E2000029", MessageUtil.getMessage("E2000029", filename));//filename[{0}] !
        }
        IOUtil.download(filename, stream, response);
    }
 public static void download(String fileName, InputStream inputStream,  HttpServletResponse response) {
        OutputStream os = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            ErrorUtil.printException(e, logger);
        } finally {
            try {
                if(os != null){
                    os.close();
                }
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

파일은 리소스/templates에서

좋은 웹페이지 즐겨찾기