본문 바로가기
스프링부트

Springboot 특정 url에서 파일 다운로드하기

특정 URL로부터 파일을 다운받아 로컬에 저장한다.

 

원격으로 특정 URL에서 파일을 받을 수 있게 된다.

 

Path를 받아서 다운 url을 수정할 수도 있겠다.

 

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;

@RestController
@Slf4j
public class d {

    @GetMapping("/jclient/download")
    public void filedownload(HttpServletResponse response) throws Exception {

        URL url = null;
        InputStream in = null;
        FileOutputStream fileOutputStream = null;
        try {

            String storeUrl = "Jsolution";
            String fileName = "jclient.jar";
            storeUrl = pathValidation(storeUrl.split("/"));
            File file = new File(storeUrl+"/"+fileName);
            fileOutputStream = new FileOutputStream(file, false); // true 시 기존 파일이 남아있음, false 시 덮어씌움

            //파일이 존재하는 위치의 URL
            String fileUrl = "https://www.apple.com/v/apple-events/home/u/images/meta/overview__bcphzsdb4fpu_og.png?202203050726";

            url = new URL(fileUrl);
            // 만약 프로토콜이 https 라면 https SSL을 무시하는 로직을 수행해주어야 한다.('https 인증서 무시' 라는 키워드로 구글에 검색하면 많이 나옵니다.)

            in = url.openStream();

            log.info("파일 다운 시작!");
            while(true){
                //파일을 읽어온다.
                int data = in.read();
                if(data == -1){
                    log.info("파일 다운 종료!");
                    break;
                }
                //파일을 쓴다.
                fileOutputStream.write(data);
            }

            in.close();
            fileOutputStream.close();

        } catch (Exception e) {
            log.error(e.getMessage(),e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            if(in != null) in.close();
            if(fileOutputStream != null) fileOutputStream.close();
        }

    }

    public String pathValidation(String... paths) throws IOException {
        String filePath = "C:/";
        File dirFile = new File(filePath);
        // 루트 폴더가 존재하는지 확인 및 없으면 생성.
        log.info("파일이 있나요? : {}", dirFile.exists());
        if (!dirFile.exists()) Files.createDirectory(dirFile.toPath());

        // 하위 경로로 들어갈때, 해당 폴더가 없으면 오류가 발생함.
        // 이를 해결하기 위해 폴더 체크 및 생성
        for (int i = 0; i < paths.length; i++) {
            filePath = filePath + "/" + paths[i];
            log.info("for filePath : {}", filePath);
            dirFile = new File(filePath);
            if (!dirFile.exists()) Files.createDirectory(dirFile.toPath());
        }
        // 전체 경로를 반환한다.
        return filePath;
    }

}