파일업로드 정리(java,spring)

이승훈·2021년 6월 25일
0

spring

목록 보기
1/2

본 소스는 기본path를 지정해놓았으나 xml에 global path를 등록후 사용해야 편리하며 실제 리눅스서버의 경로를 관리할 수 있습니다.

	//이미지, 파일경로, depth는 유저별 폴더를 분류하는경우
	/* How to use */
	//     1. String path = request.getSession().getServletContext().getRealPath("uploadImg");에 기본 업로드패스가 지정된다.
	//     2. 사용자는 parameter중 filePath와 depth만 신경쓰면된다.
	//	   3. filePath는 대분류를 나타낸다. ex)profile, product, 등등 
	//	   4. depth는 소분류(user_pk)를 나타낸다. ex)profile중 user_pk가 2인 유저
	//	   5. 다형성을 통해 대분류, 소분류가 각각 필요하거나 필요하지 않은경우를 null이 아닌 parameter 자체를 안받고 사용가능하게 함
	public static String uploadFile(MultipartFile multiFile, String filePath, HttpServletRequest request, String depth) {
		String fileName = multiFile.getOriginalFilename();//db저장될 파일명
		// System.out.println("mulitFile : "+fileName);
		String path = request.getSession().getServletContext().getRealPath("/resources/uploadImg");
		if(filePath != null) {
			path= path+"/"+filePath;
		}
		if(depth != null){
			path= path+"/"+depth;
		}
		path+="/";	
		System.out.println("path : "+path);
		
		File file = new File(path);
		if(!file.exists()) {//없으면 생성
			System.out.println("경로 : "+path);
			file.mkdirs();
		}
		
		byte[] bytes;
		file = new File(path,multiFile.getOriginalFilename());
		System.out.println("fileName : "+multiFile.getOriginalFilename());
		
		
		
		try {
			bytes = multiFile.getBytes();
			FileCopyUtils.copy(bytes, file);//spring method
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		return fileName;
	}
	
	//다형성으로 폴더세분화, 유저별폴더정리 정의
	public static String uploadFile(MultipartFile multiFile,  HttpServletRequest request) {
		 return uploadFile( multiFile, null,  request, null);
	}
	
	public static String uploadFile(MultipartFile multiFile, String filePath, HttpServletRequest request) {
		 return uploadFile( multiFile, filePath,  request, null);
	}
	public static String uploadFile(MultipartFile multiFile, HttpServletRequest request,String depth) {
		 return uploadFile( multiFile, null,  request, depth);
	}

0개의 댓글