MVC2 FINAL STEP

최보현·2022년 8월 23일
0

MVC

목록 보기
18/18
post-thumbnail

스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 - sec11
출처 : 스프링 MVC 2편

개인적으로 제일 싫어하는 강의류들이 보통 파일 관련인데 망할 윈도우 경로 설정 극헬수준

파일 업로드

HTML 폼 전송 방식

크게 2가지로 나뉨

  • application/x-www-form-urlencoded
    가장 기본적인 방법으로, Form 태그에 별도의 enctype 옵션이 없으면 웹 브라우저는 요청 HTTP 메시지의 헤더에 Content-Type: application/x-www-form-urlencoded 을 추가함
    폼에 입력한 전송할 항목을 HTTP Body에 문자로 username=kim&age=20 와 같이 파라미터 형식으로 전송함

파일을 업로드 하려면 파일은 문자가 아니라 바이너리 데이터를 전송해야 함
문자를 전송하는 이 방식으로 파일을 전송하기는 난이도 헬 + 보통 폼을 전송할 때 파일만 전송하지 않음(문자랑 바이너리를 동시에 전송해야 하는 상황 발생)

  • multipart/form-data
    위의 방식의 문제점을 해결해줄 수 있는 친구
    매우 복잡하고 각각의 부분(Part)로 나누어져 있음
    Form 태그에 별도의 enctype="multipart/form-data" 를 지정해야 함!
    다른 종류의 여러 파일과 폼의 내용 함께 전송 가능 그래서 이름이 multipart
    폼의 입력 결과로 생성된 HTTP 메시지를 보면 각각의 전송 항목이 구분이 됨Content- Disposition 이라는 항목별 헤더가 추가되어 있고 여기에 부가 정보가 있음, 폼의 일반 데이터는 각 항목별로 문자가 전송되고, 파일의 경우 파일 이름과 Content-Type이 추가되고 바이너리 데이터가 전송됨
    이렇게 각각의 항목을 구분해서, 한번에 전송

서블릿 파일 업로드

@Slf4j
@Controller
@RequestMapping("/servlet/v1")
public class ServletUploadControllerV1 {

    @GetMapping("/upload")
    public String newFile(){
        return "upload-form";
    }

    @PostMapping("/upload")
    public String saveFileV1(HttpServletRequest request) throws ServletException, IOException {
        log.info("request={}",request);

        String itemName = request.getParameter("itemName");
        log.info("itemName={}",itemName);

        Collection<Part> parts = request.getParts();
        //multipart/form-data 전송 방식에서 각각 나누어진 부분을 받아서 확인 가능
        log.info("parts={}",parts);

        return "upload-form";
    }
}

+) application.properties에 추가해야할 옵션
Logging.level.org.apache.coyote.http11=debug => http메시지를 서버에서 로그로 변화해서 볼 수 있음

멀티파트 사용 옵션

큰 파일을 무제한하게 올리면 SizeLimitExceededException발생 그걸 방지하자

spring.servlet.multipart.max-file-size=1MB
파일 하나의 최대 사이즈 지정(디폴트값)
spring.servlet.multipart.max-request-size=10MB
멀티파트 요청 하나에 여러 파일의 합의 최대 사이즈 지정(디폴트값)

멀티파트와 관련된 내용을 실행하게 할지 말지
spring.servlet.multipart.enabled=false||true
false로 두게 되면 서블릿 컨테이너는 멀티파트와 관련된 처리를 하지 않음

request=org.apache.catalina.connector.RequestFacade@xxx
itemName=null
parts=[]

위에 결과 로그를 보면 request.getParameter("itemName") , request.getParts() 의 결과가 비어있음

true(디폴트)로 두게 되면 스프링 부트는 서블릿 컨테이너에게 멀티파트 데이터를 처리

request=org.springframework.web.multipart.support.StandardMultipartHttpServletRequest
itemName=Spring
parts=[ApplicationPart1, ApplicationPart2]

request.getParameter("itemName"), request.getParts() 에 요청한 두
가지 멀티파트의 부분 데이터가 포함됨
로그를 보면 HttpServletRequest 객체가 RequestFacade 에서 StandardMultipartHttpServletRequest 로 변환됨

실제 파일이 저장될 경로 설정

application.properties에
file.dir=파일 업로드 경로 설정(예): /Users/kimyounghan/study/file/
나같은 윈도우의 경우
file.dir=C:/Users/qhgus/Desktop/STUDY/IMG/
진짜 얘 때문에 이 강의를 던질까 오조억번 정도 고민함

서블릿 파일 업로드 Ver2.

@Slf4j
@Controller
@RequestMapping("/servlet/v2")
public class ServletUploadControllerV2 {

    @Value("${file.dir}")
    private String fileDir;
    //application.properties에서 설정한 file.dir값 주입

    @GetMapping("/upload")
    public String newFile(){
        return "upload-form";
    }

    @PostMapping("/upload")
    public String saveFileV1(HttpServletRequest request) throws ServletException, IOException {
        log.info("request={}",request);

        String itemName = request.getParameter("itemName");
        log.info("itemName={}",itemName);

        Collection<Part> parts = request.getParts();
        log.info("parts={}",parts);

        for (Part part : parts) {
            log.info("====PART====");
            log.info("name={}",part.getName());
            Collection<String> headerNames = part.getHeaderNames();
            for (String headerName : headerNames) {
                log.info("header {} : {}", headerName, part.getHeader(headerName));
            }
            //편의 메서드
            //content-disposition; filename
            log.info("submittedFilename={}", part.getSubmittedFileName());
            //클라이언트가 전달한 파일명
            log.info("size={}", part.getSize()); //part body size

            //데이터 읽기
            InputStream inputStream = part.getInputStream();
            String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
            log.info("body={}", body);

            //파일에 저장하기
            if(StringUtils.hasText(part.getSubmittedFileName())){
                String fullPath = fileDir + part.getSubmittedFileName();
                log.info("파일 저장 fullPath={}", fullPath);
                part.write(fullPath);
                //part를 통해 전송된 데이터 저장 가능
            }
        }
        return "upload-form";
    }
}

멀티파트 형식은 전송 데이터를 하나하나 각각 부분(Part)으로 나누어 전송 parts도 바디와 헤더로 구분된다는 점!

서블릿이 제공하는 Part 는 편하기는 하지만, HttpServletRequest 를 사용해야 하고, 추가로 파일 부분만 구분하려면 여러가지 코드를 넣어야 함

우리의 구세주 스프링 등장 두둥탁

스프링 파일 업로드

MultipartFile 이라는 인터페이스로 멀티파트 파일을 매우 편리하게 지원함

@Slf4j
@Controller
@RequestMapping("/spring")
public class SpringUploadController {

    @Value("${file.dir}")
    private String fileDir;

    @GetMapping("/upload")
    public String newFile(){
        return "upload-form";
    }

    @PostMapping("/upload")
    public String saveFile(@RequestParam String itemName, @RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        log.info("request={}",request);
        log.info("itemName={}",itemName);
        log.info("multipartFile={}",file);

        if (!file.isEmpty()){
            String fullPath = fileDir + file.getOriginalFilename();
            log.info("파일 저장 fullPath={}",fullPath);
            file.transferTo(new File(fullPath));
            //파일 저장
        }
        return "upload-form";
    }
}

@RequestParam MultipartFile file
=> 업로드하는 HTML Form의 name에 맞추어 @RequestParam 을 적용하면 됨! + @ModelAttribute 에서도 MultipartFile 을 동일하게 사용 가능

예제를 통한 연습

서버 내에 관리하는 파일명과 고객이 업로드한 파일명을 분리하자

uploadFileName => 고객이 업로드한 파일명
storeFileName => 서버 내부에서 관리하는 파일명
위와 같은 방식으로 분리를 해줘야 함! => 고객이 업로드한 파일명으로 서버 내부에 파일을 저장하면 ❌
WHY? 서로 다른 고객이 같은 파일이름을 업로드 하는 경우 기존 파일 이름과 충돌 가능성⬆️ 서버에서는 저장할 파일명이 겹치지 않도록 내부에서 관리하는 별도의 파일명 필요(ex. UUID 활용)

파일 저장과 관련된 로직
@Component
public class FileStore {

    @Value("${file.dir}")
    private String fileDir;

    public String getFullPath(String  filename){
        return fileDir + filename;
    }

    public List<UploadFile> storeFiles(List<MultipartFile> multipartFiles) throws IOException {
        List<UploadFile> storeFileResult = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFiles) {
            if(!multipartFile.isEmpty()){
                storeFileResult.add(storeFile(multipartFile));
            }
        }
        return storeFileResult;
    }

    public UploadFile storeFile(MultipartFile multipartFile) throws IOException {
        if(multipartFile.isEmpty()){
            return null;
        }

        String originalFilename = multipartFile.getOriginalFilename();
        //서버에 저장하는 파일명
        String storeFileName = createStoreFileName(originalFilename);
        multipartFile.transferTo(new File(getFullPath(storeFileName)));
        return new UploadFile(originalFilename, storeFileName);
    }

    private String createStoreFileName(String originalFilename) {
        String uuid = UUID.randomUUID().toString();
        //확장자 추출
        String ext = extractExt(originalFilename);
        return uuid + "." + ext;
    }

    private String extractExt(String originalFilename) {
        int pos = originalFilename.lastIndexOf(".");
       return originalFilename.substring(pos + 1);
    }
}

createStoreFileName() => 서버 내부에서 관리하는 파일명은 유일한 이름을 생성하는 UUID 를 사용해서 충돌 방지
extractExt() => 확장자를 별도로 추출해서 서버 내부에서 관리하는 파일명에도 붙여줌 ex) a.png 라는 이름으로 업로드 하면 51041c62-86e4-4274-801d-614a7d994edb.png 와 같이 저장

가장 중요한 컨트롤러

@Slf4j
@Controller
@RequiredArgsConstructor
public class ItemController {
    private final ItemRepository itemRepository;
    private final FileStore fileStore;
    
    @GetMapping("/items/new") //등록 폼 보여주기
    public String newItem(@ModelAttribute ItemForm form) {
        return "item-form";
    }
    
    @PostMapping("/items/new") //폼의 데이터를 저장 후 보여주는 화면으로 리다이렉트
    public String saveItem(@ModelAttribute ItemForm form, RedirectAttributes redirectAttributes) throws IOException {
        UploadFile attachFile = fileStore.storeFile(form.getAttachFile());
        List<UploadFile> storeImageFiles =  fileStore.storeFiles(form.getImageFiles());

        //데이터베이스에 저장
        Item item = new Item();
        item.setItemName(form.getItemName());
        item.setAttachFile(attachFile);
        item.setImageFiles(storeImageFiles);
        itemRepository.save(item);

        redirectAttributes.addAttribute("itemId", item.getId());
        return "redirect:/items/{itemId}";
    }
    
    @GetMapping("/items/{id}") //상품을 보여주기
    public String items(@PathVariable Long id, Model model) {
        Item item = itemRepository.findById(id);
        model.addAttribute("item", item);
        return "item-view";
    }
    
    @ResponseBody
    @GetMapping("/images/{filename}") //이미지 조회시 사용
    public Resource downloadImage(@PathVariable String filename) throws MalformedURLException {
        return new UrlResource("file:" + fileStore.getFullPath(filename));
        //UrlResource로 이미지 파일을 읽어서 @ResponseBody로 이미지 바이너리 반환
    }
    
    @GetMapping("/attach/{itemId}") //파일을 다운로드 할 때
    public ResponseEntity<Resource> downloadAttach(@PathVariable Long itemId) throws MalformedURLException {
        Item item = itemRepository.findById(itemId);
        String storeFileName = item.getAttachFile().getStoreFileName();
        String uploadFileName = item.getAttachFile().getUploadFileName();
        UrlResource resource = new UrlResource("file:" + fileStore.getFullPath(storeFileName));

        log.info("uploadFileName={}", uploadFileName);

        String encodedUploadFileName = UriUtils.encode(uploadFileName, StandardCharsets.UTF_8);
        String contentDisposition = "attachment; filename=\"" + encodedUploadFileName + "\"";

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                .body(resource);
    }
}

다운로드를 할 때, 고객이 업로드한 파일 이름으로 다운로드 할 수 있게 하는 것이 좋음 => Content-Disposition 해더에 attachment; filename="업로드 파일명" 값을 주면 됨!

다중 파일 업로드를 하려면 해야 할 것

타임리프에서 multiple="multiple" 옵션을 주면 됨!

서버에서는 실제 파일 자체를 저장하는 것이 아닌 경로를 저장한다.

profile
Novice Developer's Blog

0개의 댓글