업로드 파일

일단 ProductVO에 파일을 받을 vo 변수 하나 생성

// 상품이미지 파일(업로드)
// <input type="file" class="form-control" name="uploadFile" multiple>
// name이 값을 가져옴
private MultipartFile uploadFile;

위의 jsp파일에서 name의 값과 일치시켜준다

그리고 util 패키지를 생성해서 업로드파일 클래스를 생성

자체적으로 사용할 2가지 메서들 만든다.

  1. 날짜를 기준으로 폴더를 생성하는 메서드 생성
  2. 이미지 파일인지를 체크해주는 메서드 생성
// 날짜를 이용한 업로드 폴더생성 및 폴더이름 반환
public static String getFolder() {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    Date date = new Date();

    String str = sdf.format(date);

    return str.replace("-", File.separator);
}

//이미지 파일여부 체크
private static boolean checkImageType(File saveFile) {

    boolean isImage = false;

    try {

        String contentType = Files.probeContentType(saveFile.toPath()); // text/html, text/plain, image/jpeg

        isImage = contentType.startsWith("image");

    } catch(Exception e) {
        e.printStackTrace();
    }

    return isImage;
}

그후 위에서 2가지 메서드를 이용해 jsp에서 가져온 값과 uploadFoler를 변수로 받아와서 1번 파일을 통해 업로드 폴더 생성후 uuid+폴더경로+날짜를 합쳐서 복사를 해서 파일을 반환

public class UploadFileUtils {

	// 업로드시 날짜폴더 생성해서 파일관리.
	// Thumnail 이미지 생성
	// byte[] 배열로 다운로드.

	// 1) 파일업로드 작업. 리턴값 : 업로드한 실제파일명(DB저장)
	public static String uploadFile(String uploadFolder, String uploadDateFolderPath, MultipartFile uploadFile) {

		String uploadFileName = ""; // 실제 업로드한 파일명
		
		// 1)업로드 날짜폴더 생성
		// String uploadDateFolderPath = getFolder(); // "2022\06\30"
		File uploadPath = new File(uploadFolder, uploadDateFolderPath); // C:\\Dev\\upload\\2022\\07\\19
		
		// 폴더 존재여부 폴더 없으면 생성하도록 설계
		if(uploadPath.exists() == false) {
			uploadPath.mkdirs(); // 하위 디렉토리 생성
		}
		
		// 클라이언트에서 업로드한 파일명
		String uploadClientFileName = uploadFile.getOriginalFilename();
		
		// 중복되지 않는 문자열 생성
		UUID uuid = UUID.randomUUID();
		
		// 중복되지 않는 파일이름을 생성_원래 파일이름 생성
		uploadFileName = uuid.toString() + "_" + uploadClientFileName;
		
		
		try {
			// 유일한 파일이름으로 객체생성
			File saveFile = new File(uploadPath, uploadClientFileName);
			uploadFile.transferTo(saveFile); // 파일업로드 됨(파일복사)
			
			if(checkImageType(saveFile)) {
				
				// 섬네일 작업 : 원본이미지를 대상으로 사본이미지를 해상도의 손실을 줄이고, 크기를 작게 작업한다
				FileOutputStream thumbnail = new FileOutputStream(new File(uploadPath, "s_" + uploadFileName));
				
				Thumbnailator.createThumbnail(uploadFile.getInputStream(), thumbnail, 100, 100);
				
				thumbnail.close();
				
			}
			
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		
		
		return uploadFileName; // 실제 업로드한 파일명(날짜폴더명 포함)
	}
}

이후 해당 변수를 컨트롤러에서 PostMapping방식으로 불러와 DB에 있는 변수에 넣어준다

그전까지는 DB의 이미지파일변수에 상태는 null이었다.

다른곳에서 다 만들어서 컨트롤러에서는 주입만 하는 방법

하지만, 먼저 파일경로를 설정하는 bean을 생성후, @Resource로 받아와야 한다

servlet-context.xml에 bean생성

<!-- 파일이 저장될 경로 설정 -->
<beans:bean id="uploadPath" class="java.lang.String">
    <beans:constructor-arg value="C:\\Dev\\upload\\"></beans:constructor-arg>
</beans:bean>

컨트롤러에 어노테이션 통해 생성

// name이 servlet-context의  bean id와 같아야 함
@Resource(name = "uploadPath")
private String uploadPath; // "C:/Dev/upload"

이후 위를 사용해 아래 작성

//상품저장
@PostMapping("/productInsert")
public String productInsert(ProductVO vo, RedirectAttributes rttr) {

    log.info("상품등록정보 : " + vo);

    // 파일업로드 작업
    // vo.getPdt_img() null 상태
    // 이미지 파일명이 저장될 pdt_img 필드에 업로드한 후 실제 파일명을 저장한다
    String uploadDateFolderPath = UploadFileUtils.getFolder();
    vo.setPdt_img_folder(uploadDateFolderPath); // 날짜폴더명
    vo.setPdt_img(UploadFileUtils.uploadFile(uploadPath, uploadDateFolderPath, vo.getUploadFile())); // 실제 업로드한 파일명


    // 상품정보저장

    return "/redirect:/상품목록주소";
}

댓글남기기