티스토리 뷰

정처기 실기 + 방통대 기말고사를 끝내고 컴백했습니다...

물론 그동안 프로젝트를 병행하며 공부했지만, 노션에만 매일 기록해놓고 미처 블로그에는 업로드를 못했네요 😱

오늘부터 노션에 기록했던 내용들을 정리하여 다시 기록해보겠습니다!

 


 

[ 전체코드 ]

GalleryService.java

더보기
package com.example.demo.service;

import com.example.demo.dto.GalleryDTO;
import com.example.demo.entity.GalleryEntity;
import com.example.demo.repository.GalleryRepository;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;


@Service
@Log4j2
public class GalleryService {
	
	@Autowired
	private GalleryRepository galleryRepository;

	// 업로드 할 위치
	@Value("${part.upload.path}")
	private String uploadPath;

	public List<GalleryDTO> createGallery(List<MultipartFile> uploadFiles) {
        List<GalleryDTO> galleryDTOList = new ArrayList<>();

        Path savePath=null;
        String fileExtension=null;

        for (MultipartFile uploadFile : uploadFiles) {
            // 이미지 파일만 업로드
            if (!Objects.requireNonNull(uploadFile.getContentType()).startsWith("image")) {
                log.warn("this file is not an image type");
                continue;
            }

            // 파일명: 업로드 된 파일의 원래 파일 이름을 추출
            String originalName = uploadFile.getOriginalFilename();

            // 마지막으로 온 "/"부분으로부터 +1 해준 부분부터 출력
            // originalName이 "/path/to/file/example.txt"와 같은 문자열이라면, "example.txt" 부분만 (파일명만) 추출
            String fileName = originalName.substring(originalName.lastIndexOf("//") + 1);
            log.info("fileName: " + fileName);

						// 파일 확장자
            fileExtension = StringUtils.getFilenameExtension(originalName);

            // 날짜 폴더 생성
            String folderPath = makeFolder();

            // UUID
            String uuid = UUID.randomUUID().toString();

            // 저장할 파일 이름 중간에 "_"를 이용하여 구분
            String saveName = uploadPath + File.separator + folderPath + File.separator + uuid + "_" + fileName;

            // Paths.get() 메서드는 특정 경로의 파일 정보를 가져옵니다.(경로 정의하기)
            savePath = Paths.get(saveName);

            try {
                // transferTo(file) : uploadFile에 파일을 업로드 하는 메서드
                uploadFile.transferTo(savePath);
                galleryDTOList.add(new GalleryDTO(fileName, uuid, folderPath));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        GalleryEntity galleryEntity = GalleryEntity.builder()
                .gallDate(Date.valueOf(LocalDate.now()))
                .gallImg(String.valueOf(savePath))
                .gallExtension(fileExtension)
                .build();

        galleryRepository.save(galleryEntity);

        return galleryDTOList;
    }

 

가볍게 엔터티, 리포지토리, 디티오의 개념을 정리하고 시작하겠습니다.

💡 Entity vs Repository vs DTO
galleryEntity 는 데이터베이스 테이블의 레코드를 나타내는 자바 객체
galleryRepository 는 데이터베이스와의 상호작용을 담당하는 인터페이스
galleryDTO 는 데이터 전송을 위한 순수한 데이터 객체 (클라이언트가 필요로 하는 데이터만을 포함

 

 

 

[ 추가된 부분 ] 

  • createGallery() 메서드
        try {
                // transferTo(file) : uploadFile에 파일을 업로드 하는 메서드
                uploadFile.transferTo(savePath);
                galleryDTOList.add(new GalleryDTO(fileName, uuid, folderPath));
            } catch (IOException e) {
                e.printStackTrace();
            }

 

galleryDTOList.add(new GalleryDTO(fileName, uuid, folderPath)); 는 이미지가 성공적으로 업로드되고 저장된 후에, 해당 이미지의 정보를 가지고 있는 GalleryDTO 객체를 galleryDTOList에 추가해줍니다.

즉, 새로운 이미지가 업로드되면 해당 이미지에 대한 정보를 GalleryDTO 객체로 만들고 이를 galleryDTOList에 추가하여 나중에 클라이언트로 반환할 수 있도록 합니다.

 

 

 

        GalleryEntity galleryEntity = GalleryEntity.builder()
                .gallDate(Date.valueOf(LocalDate.now()))
                .gallImg(String.valueOf(savePath))
                .gallExtension(fileExtension)
                .build();

        galleryRepository.save(galleryEntity);

        return galleryDTOList;
    }
  1. .gallDate(Date.valueOf(LocalDate.now())): 현재 날짜를 gallDate 필드에 저장합니다. 이를 통해 이미지가 업로드된 시간을 기록할 수 있습니다.
  2. .gallImg(String.valueOf(savePath)): 이미지 파일의 저장 경로를 gallImg 필드에 저장합니다.
  3. .gallExtension(fileExtension): 이미지 파일의 확장자를 gallExtension 필드에 저장합니다.
  4. .build(): 설정한 값들을 기반으로 GalleryEntity 객체를 생성합니다.
  5. galleryRepository.save(galleryEntity): 생성한 GalleryEntity 객체를 데이터베이스에 저장합니다.
  6. galleryDTOList 라는 리스트를 반환

 


 

 

💻 [ 결과 ]  

결과적으로 파일 경로가 DB에 잘 저장된 모습을 볼 수 있습니다!

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함