본문 바로가기

Backend/Java

자바 원격서버 파일 다운로드 (Java, Spring)

https://k.kakaocdn.net/dn/crbxqN/btqAPdDwLQJ/9IkFx8zBJcKWYHMahWrar0/img.jpg

원격 서버에 위와 같은 이미지가 있다고 가정해볼게요.

자바에서 원격 서버의 파일을 다운로드 받아서 저장하는 코드를 작성해보겠습니다.

자바 버전은 1.8 이상으로 사용해야 코드 사용 가능합니다.

Java

별도 라이브러리를 사용하지 않았어요.

 

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

 

// 원격 파일 다운로드 URL
String fileUrl = "https://k.kakaocdn.net/dn/crbxqN/btqAPdDwLQJ/9IkFx8zBJcKWYHMahWrar0/img.jpg";
String fileName = UUID.randomUUID().toString(); // 파일명 (랜덤생성)
int index = fileUrl.lastIndexOf(".");
String ext = fileUrl.substring(index); // 파일 확장자 추출
Path target = Paths.get("C:/Temp", fileName + ext); // 파일 저장 경로

try {
	URL url = new URL(fileUrl);
	InputStream in = url.openStream();
	Files.copy(in, target); // 저장
	in.close();
} catch (IOException e) {
	e.printStackTrace();
}

Spring

import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

 

// 원격 파일 다운로드 URL
String fileUrl = "https://k.kakaocdn.net/dn/crbxqN/btqAPdDwLQJ/9IkFx8zBJcKWYHMahWrar0/img.jpg";
URI url = URI.create(fileUrl);

// 원격 파일 다운로드
RestTemplate rt = new RestTemplate();
ResponseEntity<byte[]> res = rt.getForEntity(url, byte[].class);
byte[] buffer = res.getBody();

// 로컬 서버에 저장
String fileName = UUID.randomUUID().toString(); // 파일명 (랜덤생성)
String ext = "." + StringUtils.getFilenameExtension(fileUrl); // 확장자 추출
Path target = Paths.get("C:/Temp", fileName + ext); // 파일 저장 경로

try {
	FileCopyUtils.copy(buffer, target.toFile());
} catch (IOException e) {
	e.printStackTrace();
}

 

파일 URL에 파일 확장자가 노출되지 않은 경우는 Response Headers에서 Content-Type이나 Content-Disposition을 분석하여 확장자를 추출해야 합니다.

 

테스트해보면 아래와 같이 경로에 파일이 저장됨을 확인할 수 있습니다.