Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

[File업로드] Spring & File 업로드 본문

인프런/[인프런] 스프링 MVC 2

[File업로드] Spring & File 업로드

Seung__ 2021. 10. 2. 17:03
  • 스프링은 MultipartFile 이라는 인터페이스로 멀티파트 파일을 지원

 

1. SpringUploadController


@Controller
@Slf4j
@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("파일저장 full Path={}", fullPath);
            file.transferTo(new File(fullPath));
        }

        return "upload-form";
    }

}
  • @RequestParam MultipartFile file
  • 업로드하는 HTML Form의 name에 맞추어 @RequestParam 을 적용하면 된다. 
  • 추가로 @ModelAttribute 에서도 MultipartFile 을 동일하게 사용할 수 있다.
  • MultipartFile 주요 메서드
    • file.getOriginalFilename() : 업로드 파일 명
    • file.transferTo(...) : 파일 저장

 

2. GitHub : 211002 Spring, FileUpload


 

GitHub - bsh6463/FileUpload

Contribute to bsh6463/FileUpload development by creating an account on GitHub.

github.com

 

Comments