본문 바로가기

study/java

전자정부프레임워크기반 게시판 만들기 (6) 파일 업로드,다운로드

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
        <!-- file upload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
 
        <!-- MultipartHttpServletRequset -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
cs

추가후 Maven Update 꼭!!해주기

 

dispatcher-servlet.xml

1
2
3
4
5
    <!-- 파일 업로드 설정 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="100000000" /> 
        <property name="maxInMemorySize" value="100000000" /> 
    </bean>
cs

 

testMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    <!-- 게시글 삽입 -->
    <insert id="insertTest" parameterType="egovframework.example.ivory.vo.TestVo">
        <![CDATA[
        INSERT INTO test(testTitle, testContent, testName, testDate, fileName)
        VALUES(#{testTitle},#{testContent},'ivory',now(),#{fileName})
        ]]>
    </insert>
    
    <!-- 게시글 수정 -->
    <update id="updateTest" parameterType="egovframework.example.ivory.vo.TestVo">
        UPDATE test SET
        testTitle = #{testTitle}, testContent = #{testContent}, fileName = #{fileName}
        WHERE testId = #{testId}
    </update>
cs

삽입,수정부분만 fileName 추가

 

TestVo에 필드추가

1
2
private String fileName;
private MultipartFile uploadFile;
cs

+getter, setter

 

testRegister.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
        <form id="form_test" action="insertTest.do" method="post" encType="multipart/form-data">
            <table class="table table-bordered">
                <tbody>
                    <tr>
                        <th>제목</th>
                        <td><input type="text" placeholder="제목을 입력하세요." name="testTitle" class="form-control" /></td>
                    </tr>
                    <tr>
                        <th>내용</th>
                        <td><textarea placeholder="내용을 입력하세요 ." name="testContent" class="form-control" style="height: 200px;"></textarea></td>
                    </tr>
                    <tr>
                        <th>첨부파일</th>
                        <td><input type="file" name="uploadFile"></td>    
                    </tr>
                    <tr>
                        <td colspan="2">
                            <button id="btn_register" type="button" class="btn_register">등록</button>
                            <button id="btn_previous" type="button" class="btn_previous">이전</button>
                    </tr>
 
                </tbody>
            </table>
        </form>
cs

form에 encType="multipart/form-data" 추가, 첨부파일 input 추가

TestController.java

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
39
40
41
42
43
44
45
    // 글쓰기
    @RequestMapping(value = "/insertTest.do")
    public String write(@ModelAttribute("testVo") TestVo testVo) throws Exception {
 
        // 파일 업로드 처리
        String fileName = null;
        MultipartFile uploadFile = testVo.getUploadFile();
        if (!uploadFile.isEmpty()) {
            String originalFileName = uploadFile.getOriginalFilename();
            String ext = FilenameUtils.getExtension(originalFileName); // 확장자 구하기
            UUID uuid = UUID.randomUUID(); // UUID 구하기
            fileName = uuid + "." + ext;
            uploadFile.transferTo(new File("D:\\upload\\" + fileName));
        }
        testVo.setFileName(fileName);
 
        System.out.println(testVo.getFileName());
 
        testService.insertTest(testVo);
 
        return "redirect:testList.do";
    }
 
    // 글수정
    @RequestMapping(value = "/updateTest.do")
    public String updateTest(@ModelAttribute("testVo") TestVo testVo, HttpServletRequest request) throws Exception {
        
        // 파일 업로드
        String fileName = null;
        MultipartFile uploadFile = testVo.getUploadFile();
        if (!uploadFile.isEmpty()) {
            String originalFileName = uploadFile.getOriginalFilename();
            String ext = FilenameUtils.getExtension(originalFileName); // 확장자구하기
            UUID uuid = UUID.randomUUID(); // uuid구하기
            fileName = uuid + "." + ext;
            uploadFile.transferTo(new File("D:\\upload\\" + fileName));
            testVo.setFileName(fileName);
        }else{
            testService.updateTest(testVo);
            return "redirect:testDetail.do?testId=" + testVo.getTestId();
        }
        
        testService.updateTest(testVo);
        return "redirect:testDetail.do?testId=" + testVo.getTestId();
    }
cs
 

파일 업로드 완료

 

FileDownloadController클래스 생성

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package egovframework.example.ivory.controller;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class FileDownloadController {
 
    @RequestMapping(value = "fileDownload.do")
    public void fileDownload(HttpServletRequest request, HttpServletResponse response) throws Exception {
 
        String filename = request.getParameter("fileName");
        String realFilename = "";
        System.out.println(filename);
 
        try {
 
            String browser = request.getHeader("User-Agent");
            // 파일 인코딩
            if (browser.contains("MSIE"|| browser.contains("Trident"|| browser.contains("Chrome")) {
                filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+""%20");
            } else {
                filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
            }
 
        } catch (UnsupportedEncodingException e) {
 
            System.out.println("UnsupportedEncodingException 발생");
 
        }
 
        realFilename = "D:\\upload\\" + filename;
        System.out.println(realFilename);
 
        File file = new File(realFilename);
        if (!file.exists()) {
            return;
        }
 
        // 파일명 지정
        response.setContentType("application/octer-stream");
        response.setHeader("Content-Transfer-Encoding""binary");
        response.setHeader("Content-Disposition""attachment; filename=\"" + filename + "\"");
 
        try {
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(realFilename);
 
            int cnt = 0;
            byte[] bytes = new byte[512];
 
            while ((cnt = fis.read(bytes)) != -1) {
                os.write(bytes, 0, cnt);
            }
 
            fis.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
}
 
cs

 

testDetail.jsp

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Board Detail</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
    integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
    crossorigin="anonymous">
 
<!-- Optional theme -->
<link rel="stylesheet"
    integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
    crossorigin="anonymous">
</head>
<body>
    <br />
    <h1 class="text-center">Board Detail</h1>
    <br />
    <br />
    <div class="container">
        <form action="updateTest.do" id="viewForm" method="post" encType="multipart/form-data">
            <table class="table table-bordered">
                <tbody>
                    <tr>
                        <th>글번호</th>
                        <td><input name="testId" type="text" value="${vo.testId}" class="form-control" readonly /></td>
                    </tr>
                    <tr>
                        <th>제목</th>
                        <td><input type="text" value="${vo.testTitle}" name="testTitle" class="form-control" /></td>
                    </tr>
                    <tr>
                        <th>내용</th>
                        <td><textarea name="testContent" class="form-control" style="height: 200px;">${vo.testContent}</textarea></td>
 
                    </tr>
                    <tr>
                        <c:if test="${vo.fileName ne null}">
                            <tr>
                                <th>다운로드</th>
                                <td><a href="fileDownload.do?fileName=${vo.fileName}">
                                    <input type="text" id="filename" value="${vo.fileName}" name="fileName" class="form-control" readonly="readonly" /></a>
                                    <button id="filedelete" type="button" class="btn_previous" style="float: right">파일삭제</button>
                            </tr>
                        </c:if>
                    </tr>
                    <tr>
                        <th>첨부파일</th>
                        <td><input type="file" name="uploadFile"></td>
                    </tr>
                    <tr>
                        <td colspan="2" style="text-align: right;">
                            <button id="btn_previous" type="button" class="btn_previous">이전</button>
                            <button id="btn_modify" type="button" class="btn_register">수정</button>
                            <button id="btn_delete" type="button" class="btn_delete">삭제</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </form>
    </div>
<!-- Latest compiled and minified JavaScript -->
<script
    integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
    crossorigin="anonymous"></script>
<script type="text/javascript">
    $(document).on('click''#btn_modify'function(e) {
        if (confirm("정말 수정하시겠습니까 ?"== true) {
            $("#viewForm").submit();
        } else {
            return;
        }
    });
    $(document).on('click''#btn_delete'function(e) {
        
        var testId = ${vo.testId};
        
        if (confirm("정말 삭제하시겠습니까 ?"== true) {
            $("#viewForm").attr("action""deleteTest.do?testId="+testId);
            $("#viewForm").submit();
        } else {
            return;
        }
    });
 
    //이전 클릭 시 testList로 이동
    $("#btn_previous").click(function previous() {
        $(location).attr('href''testList.do');
 
    });
    
    $("#filedelete").click(function deletefile() {
        $('#filename').val(null);
 
    });
</script>
</body>
</html>
cs

마찬가지로 form에 encType="multipart/form-data" 추가,

다운로드, 첨부파일 항목을 추가해주고 파일삭제버튼을 눌렀을때 작동할 script문을 추가해준다.

 

파일 다운로드 완료



출처: https://ivory-room.tistory.com/64?category=875739 [개발로 자기개발]