본문 바로가기
업무 기록/API

Spring 이미지 업로드 (파일생성, 난수, 경로 설정)

by code2772 2023. 6. 17.

[ 목차 ]

    728x90
    반응형

    ✔ 이미지 저장, 경로, 파일이름 

    // 이미지 저장, 경로, 파일이름
    private String saveImage(MultipartFile image, String storagePath, String filename, String type) {
       try {
          String savePath = UPLOAD_DIRECTOR_STRING + storagePath;
          File storageDirectory = new File(savePath);
          if(!storageDirectory.exists()) {
             storageDirectory.mkdirs(); // 파일 경로가 없는 경우 디렉토리를 생성
          }
          File imageFile = new File(storageDirectory, filename);
    
          image.transferTo(imageFile); // 이미지 파일을 해당 경로에 저장
          // 파일 형시 포함하여 저장
          String fileFormat = StringUtils.getFilenameExtension(image.getOriginalFilename());
          String filenameWithoutFormat = StringUtils.stripFilenameExtension(filename);
          String filenameWithFormat = filenameWithoutFormat + "." + fileFormat;
    
          String randomPath = generateRandomPath();
    
          String imageUrl = BASE_URL + "/a/b/c/d/" + type + "/" +storagePath + "/" + filenameWithFormat;
    
          System.out.println("File Saved Path : " + imageFile.getAbsolutePath());
          System.out.println("Image URL : " + imageUrl);
          return imageUrl;
    
       }catch(IOException e) {
          e.printStackTrace();
          return null;
    
       }
    
    }

     

    ❗ 부연설명

    private String saveImage(MultipartFile image, String storagePath, String filename, String type) {

    MultipartFile 유형의 'image'(업로드된 이미지 파일로 가정), 이미지가 저장될 디렉토리 경로를 나타내는 문자열인 'storagePath', 'filename'의 네 가지 매개변수를 취하는 'saveImage'라는 메서드이다. 저장된 이미지에 대해 원하는 파일 이름을 나타내는 문자열이고 type`은 이미지 유형을 나타내는 문자열.

     

    ❗ 부연설명

    try {
        String savePath = UPLOAD_DIRECTOR_STRING + storagePath;
        File storageDirectory = new File(savePath);
        if(!storageDirectory.exists()) {
            storageDirectory.mkdirs(); // create directory if file path doesn't exist
        }
        File imageFile = new File(storageDirectory, filename);
    
        image.transferTo(imageFile)

    storagePath에 저장하려고 시도

    먼저 storageDirectory가 존재하는지 확인하고, 없으면 mkdirs() 메소드를 사용하여 디렉토리를 생성

    그런 다음 storageDirectory와 filename을 결합하여 파일의 전체 경로를 나타내는 File 개체 imageFile을 만든다.
     image 개체에서 transferTo() 메서드가 호출되어 imageFile을 대상으로 전달하여 이미지 파일을 지정된 경로에 저장

     

    반응형

     

    ✔ 경로 결정 메소드 

    // 경로 결정 메소드 - type에 따라 저장 경로를 결정
    private String determineStoragePath(String type) {
       String storagePath;
       switch(type) {
       case "mms":
          storagePath = "mms_storage";
          break;
       case "kak":
          storagePath = "kakao_storage";
          break;
       case "rcs":
          storagePath = "rcs_storage";
          break;
       default:
          storagePath = "default_storage";
          break;
       }
       return storagePath;
    }

    입력된 type에 따라 내가 설정한 위치에 폴더가 생성된다.

     

    ❗ 부연설명

        String fileFormat = StringUtils.getFilenameExtension(image.getOriginalFilename());
        String filenameWithoutFormat = StringUtils.stripFilenameExtension(filename);
        String filenameWithFormat = filenameWithoutFormat + "." +fileFormat;
    
        String randomPath = generateRandomPath();
    
        String imageUrl = BASE_URL + "/a/b/c/d/" + type + "/" +storagePath + "/" + filenameWithFormat;
        // String imageUrl = BASE_URL + "/" + randomPath + "/" + filenameWithFormat;
    
        System.out.println("File Saved Path : " + imageFile.getAbsolutePath());
        System.out.println("Image URL : " + imageUrl);

    ㅊStringUtils.getFilenameExtension() 메서드를 사용하여 이미지의 원래 파일 이름에서 파일 형식(확장자)을 추출

    또한 StringUtils.stripFilenameExtension() 메서드를 사용하여 지정된 filename에서 형식을 제거한다.

    그런 다음 형식이 없는 파일 이름과 추출된 파일 형식을 결합하여 filenameWithFormat을 만든다.

    generateRandomPath() 메소드가 호출되어 임의의 경로를 생성한 다음 이미지 유형 storagePath 및 filenameWithFormat과 함께 BASE_URL에 추가됩니다. 결과 imageUrl은 이미지에 액세스할 수 있는 URL을 나타내다.

    마지막으로 저장된 imageFile의 절대 경로와 imageUrl이 디버깅 목적으로 추출

     

    ✔ 폴더명 랜덤으로 생성

    private String generateRandomPart() {
       String characters = "0123456789abcdefghijqlmnopqrstuwxyzABCDEFGHIJQLMNOPQRSTUWXYZ";
       StringBuilder sb = new StringBuilder();
       Random random = new Random();
    
       for (int i=0; i < 10; i++) {
          int index = random.nextInt(characters.length());
          sb.append(characters.charAt(index));
       }
       return sb.toString();
    }

    파일 이름을 난수로 랜덤으로 출력해주는 부분이다.

    반응형