Backend/스프링부트
[Spring Boot] URL을 통해 이미지 다운받고 확장자 감지해서 저장하기
Gaejirang-e
2022. 12. 19. 13:20
[MemberService.java]
@Service
@RequiredArgsConstructor
public class MemberService {
@Value("${custom.genFileDirPath}")
private String genFileDirPath;
private final MemberRepository memberRepository;
private String getCurrentProfileImgDirName() {
return "member/" + Util.date.getCurrentDateFormatted("yyyy_MM_dd");
}
public void setProfileImgByUrl(Member member, String url) {
String filePath = Util.file.downloadImg(url, genFileDirPath + "/" + getCurrentProfileImgDirName() + "/" + UUID.randomUUID());
member.setProfileImg(getCurrentProfileImgDirName() + "/" + new File(filePath).getName());
}
}
[build.gradle]
implementation 'org.apache.tika:tika-core:2.4.1'
[Util.java]
public class Util {
public static class file {
public static String downloadImg(String url, String filePath) {
// 부모 디렉터리가 없으면 만들어라
new File(filePath).getParentFile().mkdirs();
// url을 통해 이미지를 받고 저장해라
byte[] imageBytes = new RestTemplate().getForObject(url, byte[].class);
try {
Files.write(Paths.get(filePath), imageBytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
String mimeType = null;
try {
// 확장자 감지 **
mimeType = new Tika().detect(new File(filePath));
} catch (IOException e) {
throw new RuntimeException(e);
}
// 알아낸 확장자로 바꾸기
String ext = mimeType.replaceAll("image/", "");
ext = ext.replaceAll("jpeg", "jpg");
String newFilePath = filePath + "." + ext;
// 확장자까지 붙인 바뀐파일 경로를 리턴
new File(filePath).renameTo(new File(newFilePath));
return newFilePath;
}
}
}