썸네일이미지를 사용하고 싶다면?
mvn repository에서 Thumbnailator 검색
build.gradle에
dependencies{
...
//이미지썸네일
implementation 'net.coobird:thumbnailator:0.4.8'
}
추가.
자바코드에서 사용
//썸네일경로
String thumbsname= filepath+"\\"+uuid+"_thumbs_"+filename;
//썸네일 생성 (복사할파일위치,썸네일생성경로,가로,세로)
Thumbnailator.createThumbnail(new File(최종저장경로),new File(thumbsname),150, 150);
ex01.html에서
<!-- 단일파일 업로드 -->
<form action="upload_ok" method="post" enctype="multipart/form-data">
<input type="file" name="file"/><br/>
<input type="submit" value="업로드"/><br/>
</form>
이전 단일파일 업로드와 똑같다. 썸네일을 만드는 건 컨트롤러에서 해결한다.
UploadController에서
@Value("${project.uploadpath}")
private String uploadpath;
//날짜별로 폴더생성
public String makeDir() {
Date date=new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
String now=sdf.format(date);
String path=uploadpath + "\\" +now; //경로
File file = new File(path);
if(file.exists()==false) {//파일이 존재하면 true
file.mkdir(); //폴더생성
}
return path;
}
//단일파일업로드
@PostMapping("/upload_ok")
public String uploadOk(@RequestParam("file") MultipartFile file) {
//파일명
String origin = file.getOriginalFilename();
//브라우저별로 경로가 포함되서 올라오는 경우가 있기에 간단한 처리.
String filename=origin.substring(origin.lastIndexOf("\\")+1);
//폴더생성
String filepath=makeDir();
//중복파일의 처리
String uuid=UUID.randomUUID().toString();
//최종저장경로
String savename=filepath+"\\"+uuid+"_"+filename;
//System.out.println(origin);
System.out.println(filename);
System.out.println(filepath);
System.out.println(uuid);
System.out.println(savename);
try {
File save = new File(savename); //세이브경로
file.transferTo(save);//업로드 진행
//썸네일경로
String thumbsname= filepath+"\\"+uuid+"_thumbs_"+filename;
//썸네일 생성 (복사할파일위치,썸네일생성경로,가로,세로)
Thumbnailator.createThumbnail(new File(savename),new File(thumbsname),150, 150);
} catch (Exception e) {
e.printStackTrace();
}
return "upload/ex01_ok";
}
try-catch문에서 썸네일 경로를 String으로 생성, 이때 경로에 _thumb_로 기존과 다르게 생성해 찾기 쉽도록.
생성한 경로와 기존 파일 생성 경로를 사용해 썸네일을 생성.
Thumbnailator.createThumbnail()의 매개변수는
복사할 파일위치, 썸네일생성, 가로크기, 세로크기.
콘솔출력문
105f024e-b718-482a-a71e-dc70a3c937ca_cat_idioms_cover.jpg
C:\upload\230221
758b87fe-67fb-42da-ac7a-374332a7247f
C:\upload\230221\758b87fe-67fb-42da-ac7a-374332a7247f_105f024e-b718-482a-a71e-dc70a3c937ca_cat_idioms_cover.jpg
이렇게 하면
파일을 업로드할 때 자동으로 기본파일과 썸네일파일 두개가 생성됨.
'Spring Boot' 카테고리의 다른 글
230222 Spring Boot 이미지파일 불러오기 (0) | 2023.02.22 |
---|---|
230221 Spring Boot 이미지 등록하기, @Transactional, selectKey (0) | 2023.02.21 |
230221 Spring Boot 파일 업로드-비동기 업로드 방식 (0) | 2023.02.21 |
230221 Spring Boot 파일 업로드 방식 (0) | 2023.02.21 |
230221 Spring Boot 파일 업로드 기초 (0) | 2023.02.21 |