구글에서 이런 예제를 본적이 있다. 이미지 url를 저장하는 방법이다.  나는 아래 코드를 이용하여 코드를 구성하였다.

 

자바 URL주소로 이미지 저장

//이미지 주소 String imagePath = "http://www.seowon.ac.kr/html/themes/kor/img/about/2_1_1960.gif"; //버퍼이미지 변수 정의 BufferedImage image = null; try { //버퍼이미지에 경로에 이미지를 읽어서 넣음..

develop88.tistory.com

    void test() {
        String imagePath = "http://www.seowon.ac.kr/html/themes/kor/img/about/2_1_1960.gif";
        BufferedImage image = null;
        try {
            image = ImageIO.read(new URL(imagePath));
            String fileNm = imagePath.substring(imagePath.lastIndexOf("/") + 1);
            File file = new File("C:/save/" + fileNm);
            ImageIO.write(image, "gif", file);

        } catch (Exception e) {

        }

 

이미지url를 업로드하는 예제 (window/Linux)등 os 체크 예제까지

spring에서는 properties 또는 yml에서 local 환경과 prod 환경을 구분하여 path를 설정할 수 있지만 현재 진행하고 있는 프로젝트는 그게 하려면 복잡하므로 그 과정을 추가 작업을 하는 로직으로 구성하였다.

- imagePath 는 이미지 주소를 인자로 주면되고 imageName는 파일로 저장할때 이름을 넣어주면된다. 당연히 확장자가 붙어 있어야한다.

    public File imageUploadToSever(String imagePath, String imageName) {
        File file = null;

        String os = System.getProperty("os.name").toLowerCase();
        BufferedImage image = null;
        try {
            image = ImageIO.read(new URL(imagePath));
            if (os.startsWith("windows")) {
                file = new File(new File("").getAbsolutePath() + "\\" + imageName);
            } else {
                file = new File(UBUNTU_BASE_PATH.getPath());
                if (!file.exists()) {
                    file.mkdirs();
                }
                file = new File(UBUNTU_BASE_PATH.getPath() + "/" + imageName);
            }

            ImageIO.write(image, imageName.substring(imageName.lastIndexOf(".") + 1), file);

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return file;
    }
@Getter
@NoArgsConstructor
public enum FileUploadType {
    PROFILE("profile/"),
    BOARD("board/"),
    UBUNTU_BASE_PATH("/home/ubuntu");

    private String path;

    FileUploadType(String path) {
        this.path = path;
    }
}
복사했습니다!