티스토리 뷰

package hello.upload.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@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(value = "itemName")String itemName, @RequestParam(value="file")MultipartFile file
                           , HttpServletRequest request) throws IOException {

        log.info("request = {}", request);
        log.info("itemNmae = {}", itemName);
        log.info("MultipartFile = {}", file);

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

        return "upload-form";

    }

}

 

스프링에서는 @RequestParam 어노테이션으로 file을 자동으로 받을 수 있다. 이 전에 서블릿을 사용할 때와는 다르게 request문서에서 parts를 꺼내지 않아도 알아서 MultipartFile로 담아 준다. 지원해주는 메소드로 파일 이름도 꺼내오기 쉬워졌다.

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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
글 보관함