Apache Commons FileUpload

DeadWhale·2022년 6월 26일
0

Spring

목록 보기
13/25
post-thumbnail

Apache Commons FileUpload

스프링에서 자체적으로 지원해주는 파일 업로드 지원 라이브러리 사용법에 관해 배웠다.

원래는 COS 라이브러리를 이용해 별 짓을 다 했지만 이제는 그러지 않아도 괜찮다

뭐가 됬든 가장 먼저 해야 하는 거!

1. pom.xml 라이브러리 추가하기!!

<!-- 아파치 파일 업로드 라이브러리 -->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.4</version>
</dependency>

2. 필요한 자료들 map으로 관리

public String updateProfile(@ModelAttribute("loginMember") Member member,
                        @RequestParam("uploadImage") MultipartFile uploadImage // 업로드된 이미지
                      , @RequestParam Map<String, Object> map // input 요소들 전부
                      , HttpServletRequest req // 파일 저장 경로 탐색용
                      , RedirectAttributes ra) throws IOException {
// 경로 작성 하기
// src/main/webapp/resources/images/memberProfile

// 1) 웹 접근 경로 (/comm/resources/images/memberProfile
String webPath = "/resources/images/memberProfile/";
// 2) 서버 저장 경로 ( )
String folderPath = req.getSession().getServletContext().getRealPath(webPath);
// map에 다 저장 웹경로 ,찐 경로 , 들어온 이미지 , 회원번호
map.put("webPath", webPath);
map.put("folderPath", folderPath);
map.put("uploadImage", uploadImage);
map.put("memberNo", member.getMemberNo());

int result = service.updateProfile(map);

input type="file"만 추출해 저장하는 MultipartFile를 사용한다.

@RequestParam("uploadImage") MultipartFile uploadImage // 업로드된 이미지

Service 수행 구문

@Override
	public int updateProfile(Map<String, Object> map) throws IllegalStateException, IOException {
		// 현재 map에 들어있는 거
		// webPath , folderPath , uploadImage , delete ,emberNo

		MultipartFile file = (MultipartFile) map.get("uploadImage");
		String delete = (String) map.get("delete");

		// 프로필 이미지 삭제 여부를 확인해서
		// 삭제가 아닌 경우(==새로운 이미지로 변경된 경우) -> 업로드된 파일명은 Rename 수행
		// 삭제된 경우 Null값을 준비한다.(DB에 업데이트)

		// 변경된 파일명 저장
		String renameImage = null;

		// 0이 변경 1이 삭제
		if (delete.equals("0")) {
			// 파일명 변경
			// 로직을 만들어야 됨
			renameImage = Util.fileRename(file.getOriginalFilename());
			map.put("profileImage", map.get("webPath") + renameImage);
			// resources/images/memberProfile/ 변경된 이름
		} else {
			map.put("profileImage", null); // 삭제인 경우 null을 넣어줘야함
		}

		// DAO 호출해서 프로필 이미지 UPDATE 수행
		int result = dao.updateProfile(map);

		// DB수정 성공시 메모리에 임시 저장되어있는 이미지를 서버에 저장
		if (result > 0 && map.get("profileImage")!= null) {
			file.transferTo(new File(map.get("folderPath") + renameImage));
			// transferTo : 해당 파일을 지정된 경로 + 이름으로 저장
		}

		return result;
	}

기본적으로 처리하는 로직이 여러개가 있다
1. Map에서 이미지 삭제 여부 값을 가져와 삭제한 경우 multipart으로 저장한 profileImage를 null로 변경해 DB에 저장할때에도 Null으로 저장한다

아닐경우 renameImage이라는 우리 규칙에 맞는 이름에
넘겨받은 파일의 원본명을 가지고 변경해 저장한다
그 후 다시 map에 저장한다 이 때 웹 경로와 같이 저장해야지 웹에서 접근가능한 이미지 경로가 된다
ex) [ resources/images/memberProfile/ 변경된 이름 ]

그 후 이미지를 DB에 저장 후! 서버에 저장한다.

if (result > 0 && map.get("profileImage")!= null) {
	file.transferTo(new File(map.get("folderPath") + renameImage));
	// transferTo : 해당 파일을 지정된 경로 + 이름으로 저장
}

0개의 댓글