code-mo
code-mo
code-mo
전체 방문자
오늘
어제
  • Recode (46)
    • - Programming -
    • Language (0)
      • Java (0)
    • - Framework -
    • Spring (4)
    • - DATA -
    • DBMS (26)
      • DataBase (5)
      • SQL (20)
      • MySQL (0)
      • MariaDB (1)
    • Server (0)
    • - Dev Kit -
    • IDE (0)
      • Eclipse (0)
    • WEB (0)
    • ETC (5)
    • - Side-Project -
    • 게시판 만들기 (9)
      • JSP ➜ Spring (9)
      • Spring ✚ Ajax (0)
    • nordia (0)
    • Diablo4 (0)
      • 야만용사 (0)
    • 쿠폰 (2)

인기 글

최근 글

최근 댓글

hELLO · Designed By 정상우.
code-mo
게시판 만들기/JSP ➜ Spring

[Spring] 파일 업로드/다운로드

[Spring] 파일 업로드/다운로드
게시판 만들기/JSP ➜ Spring

[Spring] 파일 업로드/다운로드

2023. 2. 13. 07:30
728x90

1. Maven 라이브러리추가

pom.xml

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2.2</version>
</dependency>
 
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
 
<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.1</version>
</dependency>
cs

 

2. 업로드 폴더 경로 및 업로드 처리 설정

servlet-context.xml

<beans:constructor-arg value="업로드 경로"></beans:constructor-arg>
property 타입 설명 
maxUploadSize long  최대 업로드 가능한 바이트 크기
maxInMemorySize int  디스크에 임시 파일을 생성하기 전에 메모리에 보관할수있는 최대 바이트크기. 기본 값은 10240 바이트이다.
defaultEncoding String  요청을 파싱할 때 사용할 캐릭터 인코딩. 지정하지 않을 경우, HttpServletRequest.setCharacterEncoding() 메서드로 지정한 캐릭터 셋이 사용. 아무 값도 없을 경우 ISO-8859-1을 사용.
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <beans:property name="maxUploadSize" value="10485760"></beans:property>
</beans:bean>
 
<beans:bean id="uploadPath" class="java.lang.String">
    <beans:constructor-arg value="D:\\nordia\src\\main\\webapp\\resources\\upload"></beans:constructor-arg>
</beans:bean>
cs

 

3. JSP 업로드 페이지

 

form 태그에 전송방식을 method대신 enctype="multipart/form-data"를 추가해 줌
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
<form action="writeAct" enctype="multipart/form-data">
    <table class="table table-striped"
        style="text-align: center; border: 1px solid #dddddd">
        <thead>
            <tr>
                <th colspan="2"
                    style="background-color: #eeeeee; text-align: center;">게시판
                    글쓰기 양식</th>
        </thead>
        <tbody>
            <tr>
                <td><input type="text" class="form-control"
                    placeholder="글 제목" name="bbsTitle" maxlength="50"></td>
            </tr>
            <tr>
                <td><textarea class="form-control" placeholder="글 내용"
                        name="bbsContent" maxlength="2048" style="height: 350px;"></textarea></td>
            </tr>
            <tr>
                <td><input type="file" name="file"></td>
            </tr>
        </tbody>
    </table>
    <input type="submit" class="btn btn-primary pull-right" value="글쓰기">
</form>
cs

 

4. 파일 업로드 Controller

UUID를 이용아혀 첨부파일의 이름을 고유식별자를 부여함으로써 다른 사용자가 같은 이름의 파일을 업로드하였을 때
덮어쓰기를 하여 기존에 있던 파일이 없어지는 상황을 방지한다.
첨부파일은 지정된 경로에 저장하고, 파일의 이름을 이용하여 데이터베이스에 저장하여 업로드, 다운로드 관리
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//게시글 작성
@RequestMapping(value = "/writeAct", method = RequestMethod.POST)
public String joinAct(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws Exception {
    BoardDTO boardDTO = new BoardDTO();
                    
    String userID = (String)request.getSession().getAttribute("userID");
    int bbsMaxNum = boardSvc.selectBoardMaxNum();
    boardDTO.setBbsID(bbsMaxNum);
    boardDTO.setBbsTitle(request.getParameter("bbsTitle"));
    boardDTO.setUserID(userID);
    boardDTO.setBbsContent(request.getParameter("bbsContent"));
    
    // 파일이름 => 랜덤문자_파일이름
    UUID uuid=UUID.randomUUID();
    String fileName=uuid.toString()+"_"+file.getOriginalFilename();
    // 업로드 파일을 => resources/upload 폴더 복사
    File uploadFile=new File(uploadPath,fileName);
    FileCopyUtils.copy(file.getBytes(), uploadFile);        
    boardDTO.setFile(fileName);
    
    boardSvc.insertBoard(boardDTO);
    return "redirect:/board";
}
cs

 

4. 파일 업로드 Service

1
2
3
4
//게시글 작성
public void insertBoard(BoardDTO boardDTO) {
    session.insert("insertBoard", boardDTO);
}
cs

 

5. 파일 업로드 쿼리

기존 테이블에 file 컬럼을 추가
`file` varchar(100) DEFAULT NULL,
1
2
3
4
5
<!-- 게시글 작성 -->
<insert id="insertBoard" parameterType="com.board.BoardDTO">
    INSERT INTO bbs.bbs (bbsID, bbsTitle, userID, bbsDate, bbsContent, file)
    VALUES (#{bbsID}, #{bbsTitle}, #{userID}, NOW(), #{bbsContent}, #{file})
</insert>
cs

 

5. 파일 다운로드 페이지

다운로드 경로를 직접 명시하게 되어있어 보안상 좋은 코드로 보이지 않음
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
<table class="table table-striped"
    style="text-align: center; border: 1px solid #dddddd">
    <thead>
        <tr>
            <th colspan="3"
                style="background-color: #eeeeee; text-align: center;">게시판 글
                보기</th>
    </thead>
    <tbody>
        <tr>
            <td style="width: 20%;">글 제목</td>
            <td colspan="2">${boardDTO.bbsTitle}</td>
        </tr>
        <tr>
            <td>작성자</td>
            <td colspan="2">${boardDTO.userID}</td>
 
        </tr>
        <tr>
            <td>작성일자</td>
            <td colspan="2">${boardDTO.bbsDate}</td>
 
        </tr>
        <tr>
            <td>글 내용</td>
            <td colspan="2" style="min-height: 200px; text-align: left;">
            ${boardDTO.bbsContent}</td>
        </tr>
        <tr>
            <td>첨부파일</td>
            <td colspan="2" style="min-height: 200px; text-align: left;">
            <a href="${pageContext.request.contextPath}/resources/upload/${boardDTO.file}" download>${boardDTO.file}</a></td>
        </tr>
    </tbody>
</table>
cs

 

'게시판 만들기 > JSP ➜ Spring' 카테고리의 다른 글

[Spring]3. 게시판 구현 CRUD - 글 수정, 삭제  (0) 2023.02.11
[Spring]2. 게시판 구현 CRUD - 글 보기  (0) 2023.02.10
[Spring]1. 게시판 구현 CRUD - 글쓰기  (0) 2023.02.09
[Spring] 게시판 구현 페이징 처리  (0) 2023.02.08
[Spring] 메인 페이지/내비게이션 <jsp:include>  (0) 2023.02.07
  • 1. Maven 라이브러리추가
  • 2. 업로드 폴더 경로 및 업로드 처리 설정
  • 3. JSP 업로드 페이지
  • 4. 파일 업로드 Controller
  • 4. 파일 업로드 Service
  • 5. 파일 업로드 쿼리
  • 5. 파일 다운로드 페이지
'게시판 만들기/JSP ➜ Spring' 카테고리의 다른 글
  • [Spring]3. 게시판 구현 CRUD - 글 수정, 삭제
  • [Spring]2. 게시판 구현 CRUD - 글 보기
  • [Spring]1. 게시판 구현 CRUD - 글쓰기
  • [Spring] 게시판 구현 페이징 처리
code-mo
code-mo

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.