Spring + Ajax 섬네일 파일 생성, 이미지 파일인지 구분, 이미지 클릭 시 원본 이미지 출력

섬네일

Thumbnailator 라이브러리를 사용하하여 섬네일 파일 생성

 

 

설정

▶pom.xml

<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>

이미지 파일인지 구분

섬네일은 이미지 파일에만 적용할 수 있기 때문에 이미지 파일인지 구분한다.
아래 코드에 이미지 파일인 경우 섬네일 파일을 생성하는 것을 확인할 수 있다.
	private boolean checkImageType(File file) {

		try {
			String contentType = Files.probeContentType(file.toPath());

			return contentType.startsWith("image");

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

		return false;
	}

	@PostMapping("/uploadAjaxAction")
	public void uploadAjaxPost(MultipartFile[] uploadFile) {

		String uploadFolder = "D:\\upload";

		// make folder --------
		File uploadPath = new File(uploadFolder, getFolder());

		if (uploadPath.exists() == false) {
			uploadPath.mkdirs();
		}
		// make yyyy/MM/dd folder

		for (MultipartFile multipartFile : uploadFile) {

			String uploadFileName = multipartFile.getOriginalFilename();

			uploadFileName = uploadFileName.substring(uploadFileName.lastIndexOf("\\") + 1);
			log.info("only file name: " + uploadFileName);

			UUID uuid = UUID.randomUUID();

			uploadFileName = uuid.toString() + "_" + uploadFileName;

			try {
				File saveFile = new File(uploadPath, uploadFileName);
				multipartFile.transferTo(saveFile);
                
				// image 파일인지 체크하는 checkImageType 메소드 호출
				if (checkImageType(saveFile)) {
					
                    //맞는 경우 섬네일 파일 생성
					FileOutputStream thumbnail = new FileOutputStream(new File(uploadPath, "s_" + uploadFileName));

					Thumbnailator.createThumbnail(multipartFile.getInputStream(), thumbnail, 100, 100);

					thumbnail.close();
				}

			} catch (Exception e) {
				e.printStackTrace();
			} // end catch
		} // end for

	}

파일 업로드 시 이미지 파일인 경우 원본 파일은 그대로 저장되고 이름이 's_'로 시작하는 섬네일 파일이 생성된다.

 

  • checImageType() 메소드
    • 이미지 파일을 구분할 수 있도록 구현
  • Thumbnailator
    • InputStream과 java.io.File 객체를 이용해 파일을 생성하였다.
    • 생성시 뒤에 사이즈에 대한 부분을 파라미터로 width, height를 지정할 수 있다.