①commons-fileupload 라이브러리를 프로젝트에 빌드 처리 - 메이븐 : pom.xml
📃pom.xml
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <!-- → 파일 업로드 기능을 제공하는 라이브러리 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.5</version> </dependency>
②Spring Bean Configuration File(servlet-context.xml)에 파일 업로드 기능을 제공하는 클래스를 Spring Bean으로 등록
📃servlet-context.xml
<!-- 파일 업로드 기능을 제공하는 클래스를 Spring Bean으로 등록 --> <!-- → Spring Bean의 식별자(beanName)을 반드시 [multipartResolver]로 설정 --> <beans:bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"> <!-- maxUploadSize 필드에 최대 업로드 파일의 제한 용량(Byte)을 주입 --> <beans:property name="maxUploadSize" value="20971520"/> <!-- defaultEncoding 필드에 전달값에 대한 문자형태(캐릭터셋)을 주입 --> <beans:property name="defaultEncoding" value="utf-8"/> </beans:bean>
③MultipartHttpServletRequest 객체를 사용하여 [multipart/form-data] 형태로 전달된 값 또는 파일을 처리
📃FileController.java
※ xyz.itwill10.controller 패키지에 FileController.java 클래스 생성
package xyz.itwill10.controller; // import java.io.File; import java.io.IOException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.multipart.MultipartFile; import lombok.RequiredArgsConstructor; // //파일 업로드 처리를 위한 환경설정 방법 //1.commons-fileupload 라이브러리를 프로젝트에 빌드 처리 - 메이븐 : pom.xml //2.Spring Bean Configuration File(servlet-context.xml)에 파일 업로드 기능을 제공하는 클래스를 Spring Bean으로 등록 //3.MultipartHttpServletRequest 객체를 사용하여 [multipart/form-data] 형태로 전달된 값 또는 파일 처리 // @Controller @RequiredArgsConstructor public class FileController { //WebApplicationContext 객체(Spring Container)를 제공받아 필드에 의존성 주입 private final WebApplicationContext context; // @RequestMapping(value = "/upload", method = RequestMethod.GET) public String upload() { return "file/upload_form"; } /* //요청 처리 메소드에 MultipartHttpServletRequest 인터페이스로 매개변수를 선언하면 Front Controller에 의해 MultipartHttpServletRequest 객체를 제공받아 사용 가능 //MultipartHttpServletRequest 객체 : [multipart/form-data] 형식으로 전달된 값 또는 파일을 처리하기 위한 객체 @RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(MultipartHttpServletRequest request) throws IOException { //MultipartHttpServletRequest.getParameter(String name) : [multipart/form-data] 형식으로 전달된 값을 문자열(String 객체)로 반환하는 메소드 String uploaderName=request.getParameter("uploaderName"); // //MultipartHttpServletRequest.getFile(String name) : [multipart/form-data] 형식으로 전달된 파일을 MultipartFile 객체로 반환하는 메소드 //MultipartFile 객체 : 사용자로부터 입력되어 전달된 파일정보를 저장하기 위한 객체 MultipartFile uploadFile=request.getFile("uploadFile"); // //전달받은 파일에 대한 검증 작업 //MultipartFile.isEmpty() : MultipartFile 객체에 파일정보가 없는 경우 [false]를 반환하고 파일정보가 있는 경우 [true]를 반환하는 메소드 if(uploadFile.isEmpty()) { return "file/upload_fail"; } // //MultipartFile.getContentType() : MultipartFile 객체에 저장된 파일의 형식(MimeType)를 반환하는 메소드 System.out.println("파일 형식 = "+uploadFile.getContentType()); //MultipartFile.getBytes() : MultipartFile 객체에 저장된 파일정보를 byte 배열로 반환하는 메소드 System.out.println("파일 크기 = "+uploadFile.getBytes().length); // //전달파일을 저장하기 위한 서버 디렉토리의 시스템 경로를 반환받아 저장 String uploadDirectory=request.getServletContext().getRealPath("/resources/images/upload"); System.out.println("uploadDirectory = "+uploadDirectory); // //전달파일을 서버 디렉토리에 저장하기 위한 File 객체 생성 //File 객체 : 시스템에 존재하는 파일정보를 저장하기 위한 객체 //MultipartFile.getOriginalFilename() : 전달파일의 파일명을 반환하는 메소드 File file=new File(uploadDirectory, uploadFile.getOriginalFilename()); // //MultipartFile.transferTo(File file) : MultipartFile 객체에 저장된 파일정보를 File 객체에 저장된 파일정보로 전달하여 저장하는 메소드 - 업로드 처리 메소드 uploadFile.transferTo(file); // request.setAttribute("uploaderName", uploaderName); request.setAttribute("uploadFilename", uploadFile.getOriginalFilename()); // return "file/upload_ok"; } */ // //요청 처리 메소드에 매개변수를 작성하여 전달값과 전달파일을 제공받아 사용 가능 //→ 업로드 파일과 같은 이름의 파일이 서버 디렉토리에 존재할 경우 기존 파일 대신 업로드 //파일이 저장 - 덮어씌위기(OverWrite) //→ commons-fileupload 라이브러리에는 업로드 파일을 변경하는 기능의 클래스 미존재 //→ 업로드 파일과 같은 이름의 파일이 서버 디렉토리에 존재할 경우 업로드 파일명을 변경하는 명령 작성 필요 @RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(@RequestParam String uploaderName , @RequestParam MultipartFile uploadFile, Model model) throws IOException { if(uploadFile.isEmpty()) { return "file/upload_fail"; } // //전달파일을 저장하기 위한 서버 디렉토리의 시스템 경로를 반환받아 저장 //→ WebApplicationContext 객체(Spring Container)에게 ServletContext 객체를 제공받아 사용 String uploadDirectory=context.getServletContext().getRealPath("/resources/images/upload"); // //사용자로부터 입력되어 전달된 원본 파일명을 반환받아 저장 String originalFilename=uploadFile.getOriginalFilename(); // //서버 디렉토리에 저장하기 위한 파일정보가 저장된 File 객체 생성 File file=new File(uploadDirectory, originalFilename); // //서버 디렉토리에 저장될 파일명을 저장하기 위한 변수 //→ 초기값으로 사용자로부터 입력되어 전달된 원본 파일명을 저장 String uploadFilename=originalFilename; // //업로드 파일과 같은 이름의 파일이 서버 디렉토리에 존재할 경우 서버 디렉토리에 저장될 파일명을 구분하기 위한 식별자를 저장하기 위한 변수 int i=0; // //File.exists() : File 객체에 저장된 파일이 시스템이 존재하지 않을 경우 [false]를 반환하고 존재할 경우 [true]를 반환하는 메소드 while(file.exists()) {//업로드 파일과 같은 이름의 파일이 서버 디렉토리에 존재할 경우 반복 처리 i++; // //파일명과 확장자를 구분하기 위한 문자열(.)를 사용하여 위치값(Index)을 반환받아 저장 int index=originalFilename.lastIndexOf("."); // //원본 파일명을 이용하여 업로드 파일명 생성 uploadFilename=originalFilename.substring(0, index)+"_"+i+originalFilename.substring(index); // //서버 디렉토리에 저장될 파일명을 저장하기 위한 변수 file=new File(uploadDirectory, uploadFilename); } // uploadFile.transferTo(file); // model.addAttribute("uploaderName", uploaderName); model.addAttribute("originalFilename", originalFilename); model.addAttribute("uploadFilename", uploadFilename); // return "file/upload_ok"; } }
📃upload_form.jsp
※ WEB-INF/views/rest 폴더에 upload_form.jsp 작성
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>SPRING</title> </head> <body> <h1>파일 업로드</h1> <hr> <%-- 파일 업로드 : 클라이언트로부터 파일을 입력받아 서버 디렉토리에 저장하는 기능 --%> <%-- → 파일을 입력받아 전달하기 위한 form 태그를 사용하며 요청방식(method 속성)은 반드시 [post]로 설정하고 전달형태(enctype 속성)는 [multipart/form-data]로 설정 --%> <form action="upload" method="post" enctype="multipart/form-data"> <table> <tr> <td>업로드 이름</td> <td><input type="text" name="uploaderName"></td> </tr> <tr> <td>업로드 파일</td> <td><input type="file" name="uploadFile"></td> </tr> <tr> <td colspan="2"><button type="submit">업로드</button></td> </tr> </table> </form> </body> </html>
📃upload_fail.jsp
※ WEB-INF/views/rest 폴더에 upload_fail.jsp 작성
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>SPRING</title> </head> <body> <h1>파일 업로드 실패</h1> <hr> </body> </html>
📃upload_ok.jsp
※ WEB-INF/views/rest 폴더에 upload_ok.jsp 작성
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>SPRING</title> </head> <body> <h1>파일 업로드 성공</h1> <hr> <p>업로더 이름 = ${uploaderName }</p> <p>업로더 파일명 = ${uploadFile }</p> </body> </html>