Spring

part 5 게시물의 첨부파일 기능

paulaner80 2016. 5. 10. 16:00
반응형

part 5 게시물의 첨부파일 기능

Chapter 01 스프링 MVC 파일 업로드

1.2.1 실습을 위한 라이브러리 추가

[pom.xml]

<dependency>

<groupId>commons-fileupload</groupId>

<artifactId>commons-fileupload</artifactId>

<version>1.3.1</version>

</dependency>

<dependency>

<groupId>org.imgscalr</groupId>

<artifactId>imgscalr-lib</artifactId>

<version>4.2</version>

</dependency>


1.2.2 파일 업로드 관련 bean 설정

1. multipartResoler 설정 : 파일 업로드로 들어오는 데이터를 처리하는 객체 설정

2. 서버의 파일 저장 경로 : 파일을 저장할 경로는 상수처럼 사용되기 때문에 특정 경로를 문자열로 설정합니다.


[servlet-context.xml]


<beans:bean id="multipartResolver" 

      class="org.springframework.web.multipart.commons.CommonsFileUploadSupport">

     <beans:property name="maxUploadSize" value="10485760"></beans:property>

</beans:bean>


<beans:bean id="uploadPath" class="java.lang.String">

     <beans:constructor-arg value="C:\\zzz\\upload"></beans:constructor-arg>

</beans:bean>


1.3 일반적인 파일 업로드 이해하기

일반적인 파일 업로드는 화면에 파일을 선택하는 <input type='file'>을 만들고 원하는 파일을 선택해서 업로드 하는 형태입니다.

1.3.1 POST 방식의 파일 업로드 처리하기

web.xml에 한글 처리용 필터를 적용

<filter>

    <filter-name>encoding</filter-name>

    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

    <init-param>

        <param-name>encoding</param-name>

        <param-value>UTF-8</param-value>

    </init-param>

</filter>

<filter-mapping>

    <filter-name>encoding</filter-name>

    <url-pattern>/*</url-pattern>

</filter-mapping>


파일 업로드를 했을 경우, 서버에는 업로드 된 파일 이름과 파일의 크기 등과 같은 정보를 화면에 보여줍니다.

1.3.2 업로드 파일의 저장

1.3.2.1 서버의 파일 저장 경로 [내용 옮김]

1.3.2.2 UploadController의 파일 저장

[UploadController]

@RequestMapping(value = "/uploadForm", method = RequestMethod.POST)

public void uploadForm(MultipartFile file, Model model) throws Exception {

 

logger.info("uploadForm called POST......"+uploadPath);

logger.info("originalName: " + file.getOriginalFilename());

logger.info("size: " + file.getSize());

logger.info("contentType: " + file.getContentType());

String savedName = uploadFile(file.getOriginalFilename(), file.getBytes());

model.addAttribute("savedName", savedName);

return;

 }


private String uploadFile(String originalName, byte[] fileData) throws Exception {

UUID uid = UUID.randomUUID();

String savedName = uid.toString() + "_" + originalName;

File target = new File(uploadPath, savedName);

FileCopyUtils.copy(fileData, target);

return savedName;

}

1.3.3 <iFrame>을 이용한 파일 업로드의 결과 처리

iFrame을 이용하면 화면 전환 효과를 없앨 수 있습니다.

<form> 태그의 전송은 화면에 포함된 <iFrame> 으로 전송 ->

결과페이지는 <iFrame> 내에 포함되므로 화면의 변화 없음 ->

결과 페이지에서 다시 바깥쪽(parent)의 javaScript 함수 호출


1.3.3.1 UploadController의 수정