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 |