ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • File - Upload / Download
    Java/Spring 2018. 8. 23. 17:53
    반응형

    pom.xml에서 파일 업로드에 필요한 Dependency를 추가한다.


    <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.3</version>
      </dependency>


    applicationContext.xml에서 파일 업로드 설정을 한다.


    <!-- FileUpload -->
        <bean id="multipartResolver"
             class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="maxUploadSize" value="104857600" /> <!-- 100MB -->
            <property name="defaultEncoding" value="UTF-8" />   
    </bean>


    100MB가 최대 용량이다.


    * Form 객체를 Command Object라고 부른다.


    파일업로드를 사용하기 위해 write.jsp의 form 태그에 enctype="multipart/form-data"를 입력한다.


    Spring Framework에서는 File을 MultipartFile 객체로 전달 받는다.


    * Servlet / Jsp 에서는 Upload가 불가능하다. -> Java File Transfer가 없기 때문이다.


    Commons-fileupload는 file을 byte단위로 바꿔서 전송하고 보안때문에 파일명과 확장자를 난수로 올리고, 중복을 없앤다.


    MultipartFile uploadFile = boardVO.getFile();
    if( !uploadFile.isEmpty() ) {
    // 실제 파일이름
    String originFileName = uploadFile.getOriginalFilename();
    // 파일 시스템에 저장될 파일의 난수 이름
    String fileName = UUID.randomUUID().toString();
    // Dir이 존재 하지 않으면 mk
    File uploadDir = new File(uploadPath);
    if( !uploadDir.exists() ) {
    uploadDir.mkdirs();
    }
    // 파일이 업로드 될 경로 지정
    File destFile = new File(uploadPath, fileName);
    try {
    // upload
    uploadFile.transferTo(destFile);
    // db에 file 정보 저장하기 위한 정보 세팅
    boardVO.setOriginFileName(originFileName);
    boardVO.setFileName(fileName);
    } catch (IllegalStateException | IOException e) {
    throw new RuntimeException(e.getMessage(), e);
    }
    }


    업로드 경로는 setting.properties에서 상수 처리한다.


    # Upload path setting
    upload.path=C:/uploadFiles


    업로드 경로는 applicationContext.xml에서 상수 처리한다.


    Download 처리


    @RequestMapping("/board/download/{id}")
    public void fileDownload(
    @PathVariable int id
    , HttpServletRequest request
    , HttpServletResponse response
    ) {
    BoardVO boardVO = this.boardService.readOneBoard(id);
    String originFileName = boardVO.getOriginFileName();
    String fileName = boardVO.getFileName();
    // Windows \
    // Unix , Linux /
    try {
    // Download
    new DownloadUtil(this.uploadPath + File.separator + fileName)
    .download(request, response, originFileName);
    } catch (UnsupportedEncodingException e) {
    throw new RuntimeException(e.getMessage(), e);
    }
    }


    detail.jsp 처리


    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Spring MVC</title>
    </head>
    <body>
        
        <h1>
            제목 : ${boardVO.subject}
            <span style="font-size: 15px">작성 시간 : ${boardVO.crtDt}</span>
        </h1>
        <h2>작성자 : ${boardVO.memberVO.name}</h2>
        
        <c:if test="${not empty boardVO.originFileName}">
            <p>
                <a href="/HelloSpring/board/download/${boardVO.id}">
                    파일이름 : ${boardVO.originFileName}
                </a>
            </p>
        </c:if>
        <div>
            내용 : ${boardVO.content}
        </div>
        
        <div>
            <a href="/HelloSpring/board/delete/${boardVO.id}">삭제</a>
            <a href="/HelloSpring/board/list">목록으로 돌아가기</a>
        </div>
        
    </body>
    </html>


    반응형

    'Java > Spring' 카테고리의 다른 글

    bean config 설정 분리  (0) 2018.08.24
    Application 예외 처리  (0) 2018.08.24
    Session  (0) 2018.08.23
    Spring - JSTL  (0) 2018.08.22
    Spring - JDBC  (0) 2018.08.21

    댓글

Designed by Tistory.