Spring

[Spring] 파일저장 transferTo, InputStream OutputStream

주니어주니 2023. 6. 6. 20:35

 

경로에 파일 저장하는 코드 2가지

 

1. MultipartFile의 transferTo() - 내부적으로 FileCopyUtils의 copy()를 사용함 ! 

2. FileCopyUtils의 copy(getInputStream(), Files.newOutputStream())

 

 

 

 

예)

private final String directory = "C:\\app\\eGovFrameDev-4.0.0-64bit\\workspace\\fitness-management\\src\\main\\webapp\\resources\\images\\profile";

@PostMapping("/register")
	public String register(@Valid @ModelAttribute("userRegisterForm") UserRegisterForm userRegisterForm, BindingResult errors) throws IOException {

		MultipartFile upfile = userRegisterForm.getUpfile();
		if(!upfile.isEmpty()) {
			String filename = upfile.getOriginalFilename();
			userRegisterForm.setPhoto(filename);
			
			// 1. MultipartFile의 transferTo()
            		upfile.transferTo(new File(directory, filename));
            		// 2. FileCopyUtils의 copy()
           		FileCopyUtils.copy(upfile.getInputStream(), new FileOutputStream(new File(directory, filename)));
			
		}