파일 업로드

CHM·2022년 6월 16일
0

Spring

목록 보기
15/26

파일 업로드

<form method="post" enctype="multipart/form-data">
...
</form>
  • 멀티파트 지원 기능을 사용해야하고, 이를 위해서 MultipartResolver를 스프링 설정으로 등록해 사용한다.
  • servlet-context.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <property name="maxUploadSize" value="104857600"/>
   <property name="defaultEncoding" value="UTF-8"/> 
</bean>
  • pom.xml
    Maven Repository에서 common fileupload를 검색해 dependency 입력

  • FileUploadController.java

@Controller
@RequestMapping("/bbs")
public class FileUploadController {
   
   @PostMapping("/upload")
   public String upload(@RequestParam("file") MultipartFile file,
                        @RequestParam("name") String fileNmae,
                        Model model) {
      if(!file.isEmpty()) {  // 파일 저장 완료
         File f = new File("c://upload", file.getOriginalFilename());
         file.transferTo(f);	
      }
      model.addAttribute("fileName", fileName);	// 실제파일 이름, 전달 데이터명
      return "upload_ok";
   {
}

0개의 댓글