ABOUT ME

Java 웹 / 앱 스터디하는 개발자입니다.

Today
Yesterday
Total
  • [Spring]서버 이미지 불러오기, 다운로드
    WEB/Spring Framework 2020. 4. 2. 11:39

     

    안드로이드 앱에서 서버 로컬의 이미지를 사용해야하는 앱이 있어

    Srping으로 구현된 서버의 로컬의 이미지를 가지고와서 사용해야한다.

     


    1. 이미지 불러오기

     

    * 현재 이미지 저장 위치 : C:\test\file\

     

    1. servlet-context.xml

     

    servlet-context.xml

     

    1
    2
    3
    4
    <!-- IMAGE VIEW -->
    <resources mapping="/images/**" location="file:///C:/test/file/" />
    <resources mapping="호출할 이미지의 경로" location="실제 저장된 로컬의 경로" />

    < Servlet-context.xml>

    <

    < 호출 결과 >


     

    2. 이미지 다운로드

     * 서버 로컬 이미지를 보여주는 용도이외에 다운로드 할 수 있수있습니다.

     * 해당되는 이미지의 이미지 경로, 파일 경로등은 적절히 넣어서 사용하시면 됩니다.

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
        
    @RequestMapping(value = "/files")
        public void files(HttpServletRequest req, HttpServletResponse res) throws Exception {
            
            String realFile = "파일 경로 + 이미지 경로";
            String fileName = "이미지 ";
            
            BufferedOutputStream out = null;
            InputStream in = null;
            
            try {
                res.setContentType("image/*");
                res.setHeader("Content-Disposition""inline;filename="+fileName);
                File file = new File(realFile);
                if(file.exists()) {
                    in = new FileInputStream(file);
                    out = new BufferedOutputStream(res.getOutputStream());
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(out != null) { out.flush();}
                if(out != null) { out.close();}
                if(out != null) { in.close();}
            }
        }
     
     

     


    < 처리 결과 >

     

     

     


    참고 : https://okky.kr/article/332498

    'WEB > Spring Framework' 카테고리의 다른 글

    [Spring] web.xml - Error Page 설정  (0) 2020.03.05
Designed by Tistory.