본문 바로가기
개발관련/Spring

[Spring] 파일 업로드 구현

by joa-yo 2020. 1. 30.
반응형

개발환경

  • Eclipse
  • spring, egovFrameWork
  • Tomcat 8.5
  • oracle 11g

목차

더보기

1.  XML 파일 설정

2. 페이지 생성

3. 기눙 구현

 

1. XML 설정

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- 파일업로드/다운로드 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>
 
<!-- 파일관련 / 썸네일라이브러리 -->
<dependency>
    <groupId>org.imgscalr</groupId>
    <artifactId>imgscalr-lib</artifactId>
    <version>4.2</version>
</dependency>
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

pom.xml파일에 추가해줍니다. <dependencies>의 하위 어느위치든 편한 곳에 삽입해주시면 됩니다.

 

root-context.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--  파일업로드 용량 (10MB)-->
    <property name="maxUploadSize" value="10485760"/>
    <property name="defaultEncoding" value="UTF-8" />
  </bean>
  
  <!--  파일업로드 디렉토리 설정 -->
  <bean id="uploadPath" class="java.lang.String">
    <constructor-arg value="[프로젝트 내 폴더, 절대경로로 설정]"/>
  </bean>
 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

멤버변수의 uploadPath는 bean설정에서 해준 값을 가져온다. 디버깅 시 상대경로로 했을 때, 이클립스 실행파일이 있는 곳이 기준이 되었다. 그래서 절대 경로로 셋팅해주었더니 문제없이 해결! (좋은방법이 있다면 댓글 부탁드립니다..!)

 


 

2. 페이지 생성

좌) 파일선택 페이지 / 우) 파일 업로드 후 페이지

   코드는 동일하더라도, 페이지의 모습은 다를 수 있습니다.

파일선택 페이지

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <div class="container">
 
      <div class="py-5 text-center">
          <h2>게시판</h2>
      </div>
    
      
      <div style="margin:10% 10% 10% 10%;">
         <!--  파일첨부 -->
         <form  action="/springBoard/file/upload.do" method="post"  enctype="multipart/form-data">
             <input type="file" name="file"/>
             <input class="btn btn-primary btn-sm"  type="submit" value="업로드"/>
         </form>
     </div>
 </div>
 
 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

파일전송을 위하여 form태그에 에 action속성은 업로드 처리를 하는 url을 적어준다. method는 post, enctype은"multipart/form-data"로 설정한다.  input 중에서 type="file"을 추가하면 파일선택 버튼 및 선택된 파일의 명이 나타난다.

업로드 후 페이지

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <div class="container">
 
  <div class="py-5 text-center">
    <h2>게시판</h2>
  </div>
 
    <h3>파일이 업로드 되었습니다.</h3>
    <span>${file.originalFilename}</span>
    <span>${file.contentType}</span>
 </div>
 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

파일 업로드 후 파일의 실제 이름(OriginalFilename)과 타입(파일 형식 및 확장자)을 나타낼 수 있도록 하였다.

 


 

3. 기능구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
(importpackage 생략)
 
@Controller
@RequestMapping("/file")
public class FileController {
    
//properties에 있는 uploadPath값 가져오기
    @Resource(name="uploadPath")
    String uploadPath;
    
//이 경로는 GET방식으로만 호출이 가능 (페이지 호출)
    @RequestMapping(value="/upload", method=RequestMethod.GET)
    public String fileupload() {
        return "post/test_file.basic";
    }
    
//이 경로는 POST방식으로만 호출이 가능 (파일 등록)
    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public ModelAndView uploadForm(MultipartFile file, ModelAndView mv) {
 
        String fileName = file.getOriginalFilename();
        File target = new File(uploadPath, fileName);
        
        //경로 생성
        if ( ! new File(uploadPath).exists()) {
            new File(uploadPath).mkdirs();
        }
        //파일 복사
        try {
            FileCopyUtils.copy(file.getBytes(), target);
            mv.addObject("file", file);
        } catch(Exception e) {
            e.printStackTrace();
            mv.addObject("file""error");
        }
        //View 위치 설정
        mv.setViewName("post/test_upload.basic");
        return mv;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 
 

파일을 form으로 전송하면, 서버는 파일을 다운받아 임시로 저장해놓는다. MultipartFile는 그 파일을 의미한다. 임시로 저장된 MultipartFile을 복사하여 우리가 원하는 위치에 저장하는 것을 파일 업로드라고 한다.

 

파일 경로가 지정되어 있지 않을 경우롤 대비하여 exists()함수로 경로가 존재하는지 확인한다. 경로가 없는 것이 확인된다면 mkdirs() 를사용하여 경로를 생성할 수 있다. 경로를 생성한 뒤에 파일을 복사한다.

 

 

 

== 실무알아가기 ==

 

실무에서 첨부파일을 다뤘을 때는 위의 코드보다 훨씬 복잡하다. 필요에따라 파일 존재유무를 검사하거나, 파일의 크기, 확장자 등을 검사한다. 그리고 업로드된 첨부파일의 이름을 그대로 저장하는 것이 아니라, 첨부파일의 네이밍 규칙을 정하여 이름과 확장자를 변경하여 저장한다. 그리고 원본파일의 이름과 확장자, 첨부파일 일자 등과 같은 정보를 DB에 따로 저장해둔다. 

 

네이밍 규칙을 정할때는 파일의 이름이 겹치지 않게 잘 설정해야한다. 만약 겹치게 되면 이전에 올렸던 파일에 덮어씌워질 위험이 있다.


Tip

더보기

- 업로드 위치는 절대경로로 설정한다.

- mkdirs는 파일의 모든 경로를 생성한다. mkdir은 최종에 적혀있는 경로만을 생성하여, 생성이 불가할 경우 false를 리턴한다.

- 위의 예제는 파일명의 중복을 고려하지 않은 상태다.

 

참조

파일업로드 : https://doublesprogramming.tistory.com/127?category=736879

 

# Spring - 파일업로드 연습1 (일반적인 방식)

1. 파일 업로드 설정 1. pom.xml 파일업로드, 이미지 썸네일 관련 라이브러리 추가 파일 업로드 라이브러리 <..

doublesprogramming.tistory.com

파일경로 생성 : https://froginpot.tistory.com/51

 

[Java Tips] File.mkdir()과 File.mkdirs()의 차이점

Java API에서는 디렉토리를 생성하기 위해, File.mkdir()과 File.mkdirs(), 두 개의 API가 제공됩니다. 위 두 개의 API는 모두 디렉토리를 생성하는 기능을 하지만, 세부적으로는 약간 틀린 기능을 합니다. File.m..

froginpot.tistory.com

 

반응형

댓글