ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spring Boot Thymeleaf 외부 로컬 이미지 출력하기 , 프로젝트 경로에 파일 업로드
    개발 공부/Spring 2022. 3. 17. 09:02
    반응형
    SMALL

    웹 서버가 따로 있지 않고 그냥 PC에 설치해서 쓰는 웹사이트를 개발 중이다

     

    그래서 이미지 파일 업로드하면 해당 pc에 저장되고 그 이미지를 바로 출력해주는 기능을 개발해야하는데

    하루종일 이미지가 안떠서 고생했다!

     


    먼저 파일 업로드

     

     

    - application.properties 에 저장 경로 ' file.upload.directory '로 지정 

     

    - 업로드 한 파일 저장하는 메소드

    	@Value("${file.upload.directory}")
    	private String sfilePath; //webapp\WEB-INF / uploadImg
    
       @RequestMapping(value="/uploadimg", method= {RequestMethod.POST})
        public String uploadImg(
        		HttpServletRequest req, 
        		@RequestParam("imgFile") MultipartFile imgFile) throws IOException {
    
            String rootPath = request.getSession().getServletContext().getRealPath("/");
            String fullPath= rootPath+sfilePath;
        
        		String imgName = imgFile.getOriginalFilename();
        		String imgpath = fullPath + imgName;
    	        String newName = "uploadimg.jpg";
                
        	   if (!imgName.isEmpty()) {
    	        	File dir = new File(fullPath);
    	        	if(!dir.exists())
    	        	{
    	        		dir.mkdirs();
    	        	}
    	        	imgFile.transferTo(new File(imgpath));
    
    				//System.out.println(" sfilePath : ");
    		        imgpath=changeFileName(imgName,newName,fullPath);
    	        }
        }

     


    String rootPath = request.getSession().getServletContext().getRealPath("/"); -> 해당 프로젝트 경로 나는 webapp이 최종 경로였다!

     

    sfilepath => 내가 저장 할 프로젝트 내 위치 ex) WEB-INB/saveimg/

     

     

    내가 사용한 MultipartFile는 파일 이름 변경해서 저장이 안된다

    그래서 그대로 저장했다가 이름 바꿔주는 메소드를 따로 만들었다

     

    저장한 파일 이름 바꾸기 메소드

     

    
        private String changeFileName(String fileName,String newFileName,String saveDir){
        	String result = saveDir+fileName;
        	if(!fileName.equals("")) {
                String fullFileName = saveDir + fileName;
                String newfullFileName = saveDir + newFileName;
                 File f = new File(fullFileName);
                 File newf = new File(newfullFileName);
                 
                 if(f1.exists()) {     // 업로드된 파일명이 존재하면 Rename한다.
    
                	 if(newf.exists()) { 
    						newf.delete()
                	  }
                      File newFile = new File(newfullFileName);                  
                      f1.renameTo(newFile);   // rename...                  
                      result = newfullFileName;
                 }
            }
        	return result;
        	
        }

     

     


     

     

    이제 로컬 이미지 파일 출력하기 로컬이미지파일 띄우기

     

    이미지태그 src에 경로로 그냥 출력하면 익스플로러에서는 뜨는데 크롬과 엣지에서 뜨지 않았다

     

    이거 안떠서 하루종일 이거만했는데

    이미지를 바이트배열로 바꾼 다음에 base64로 출력하니까 출력됐다

     

    소스 -- 

     

    
    Path path1 = Paths.get(fullPath+ category.getf_path()); // 다운로드 할 파일의 최종 경로
    
    if(dir.exists()) {	
        Resource resource = new InputStreamResource(Files.newInputStream(path1)); // path1의
    
        mav.addObject("f_path",Base64.getEncoder().encodeToString(getImage(path1.toString())));
    }

     

     

     

    image file -> byte array

     public byte[] getImage(String imagePath) throws Exception {
        	 
        	try (InputStream inputStream = new FileInputStream(imagePath)){
        		
    	        byte[] byteArray = inputStream.readAllBytes();
    	        return byteArray;
    	    }catch (Exception e){
    	        return null;
    		}
        	
        }

     

     

    출력

    <img th:src="${데이터변수}? 'data:image/jpeg;base64,'+${데이터변수}:''" class="parent" id="img" style="width: inherit; width:100%;"/>

     

     

    뿌듯!

     

    반응형
    LIST

    댓글

Designed by Tistory.