Step06_FileUpload

2017. 7. 30. 18:32· FrameWork/spring
반응형
SMALL

Step06 만들고 기본 설정 해줘


이렇게 잘 뜨면 기본 설정은 다 한 것.


pom.xml 로 가서 


DB 연동해서 다운로드 및 업로드 처리를 할거야



이걸 추가해줘


추가하고 저장을 누르면


라이브러리들이 설치가 됌



잘 저장 되었으면 


Maven Dependencies 에 jar 파일들이 저장되어 있어



mybatis 패키지 만들어서 


3개 파일 Step02 에서 가져와



이거 지우고



패키지명 바뀐거 적어주고 filemapper 로 바꿔


 

FileMapper 로 이름 바꾸고



이렇게 수정해줘


servlet-context.xml 로가서



DB 연동 하려면 bean 으로 관리가 되야해





이렇게 코드를 추가해줘


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
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>classpath:com/gura/step06/mybatis/db.properties</value>
        </property>
    </bean>
    <!-- DataSource 설정 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
        <property name="driverClass" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>
    
    <!-- SqlSessionFactory 객체 -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation"
            value="classpath:com/gura/step06/mybatis/Configuration.xml"/>
    </bean>
    
    <!-- Dao 에 주입해줄 SqlSession 인터페이스를 구현한 
    SqlSessionTemplate 객체 -->
    <bean class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sessionFactory"/>
    </bean>    
    
    
    <!-- Multipart 폼 전송을 처리하기 위한 bean -->
    
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10240000"></property>
    </bean>
    
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
        <property name="order" value="0"/>
    </bean>
Colored by Color Scripter
cs



이거 추가해 준거야


파일 업로드 처리를 해야 하기에


webapp 폴더에다가 폴더 만들어




패키지 5개 추가로 더 만들어줘



dto 클래스 만들어 주고



이전거와 같은데 뭔가 하나가 더 추가됐어


Spring 에서 제공해 주는게 있어

이걸 추가해주면 파일 업로드 해줄때 뭔가 자동으로 처리해 주는게 있어


이렇게 해두고 Dto로 만들어 줘


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
package com.gura.step06.file.dto;
 
import org.springframework.web.multipart.MultipartFile;
 
public class FileDto {
    private int num;
    private String writer;
    private String title;
    private String orgFileName;
    private String saveFileName;
    private long fileSize;
    private String regdate;
    private MultipartFile file; // Spring 에서 파일 업로드 처리하기 위해
    // 생성자
    public FileDto(){}
    public FileDto(int num, String writer, String title, String orgFileName, String saveFileName, long fileSize,
            String regdate, MultipartFile file) {
        super();
        this.num = num;
        this.writer = writer;
        this.title = title;
        this.orgFileName = orgFileName;
        this.saveFileName = saveFileName;
        this.fileSize = fileSize;
        this.regdate = regdate;
        this.file = file;
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public String getWriter() {
        return writer;
    }
    public void setWriter(String writer) {
        this.writer = writer;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getOrgFileName() {
        return orgFileName;
    }
    public void setOrgFileName(String orgFileName) {
        this.orgFileName = orgFileName;
    }
    public String getSaveFileName() {
        return saveFileName;
    }
    public void setSaveFileName(String saveFileName) {
        this.saveFileName = saveFileName;
    }
    public long getFileSize() {
        return fileSize;
    }
    public void setFileSize(long fileSize) {
        this.fileSize = fileSize;
    }
    public String getRegdate() {
        return regdate;
    }
    public void setRegdate(String regdate) {
        this.regdate = regdate;
    }
    public MultipartFile getFile() {
        return file;
    }
    public void setFile(MultipartFile file) {
        this.file = file;
    }
    
    
}
 
Colored by Color Scripter
cs


Dao 로 가서 인터페이스 만들어줘




파일 삽입,삭제등 기능을 만들 걸 설정해준거야



클래스 만들어 주고



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
package com.gura.step06.file.dao;
 
import java.util.List;
 
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
import com.gura.step06.file.dto.FileDto;
 
@Repository
public class FileDaoImpl implements FileDao{
 
    //의존객체
    @Autowired
    private SqlSession session;
    
    @Override
    public void insert(FileDto dto) {
        session.insert("file.insert", dto);
    }
 
    @Override
    public void delete(int num) {
        session.delete("file.delete", num);
    }
 
    @Override
    public List<FileDto> getList() {
        List<FileDto> list=session.selectList("file.getList");
        return list;
    }
 
    @Override
    public FileDto getData(int num) {
        FileDto dto=session.selectOne("file.getData", num);
        return dto;
    }
 
}
 
Colored by Color Scripter
cs

이렇게 미리 완성 시켜놔


다 뻔한작업이라 가능한것





이제 여기에 해당하는 Mapper 만들면 돼

configuration 에 alis 미리 정의



이제 Mapper 로~



이렇게 Mapper 완성해줘


board_data 라고 만들어 놓은 테이블에 삽입, 삭제, 리스트 가져오는 것, 데이터 가져오는 sql 문이야


파일에 관련된 비지니스 로직을 처리할 서비스 만들러

서비스 패키지로~




인터페이스 만들고



이렇게 코딩


리퀘스트가 왜 필요한지는 서비스를 구현하다 보면 알거야


리퀘스트에 있는 어떤 정보가 필요해서 구현을 한거야


Impl 클래스 만들고



컴퍼넌트 스캔이 일너 났을때 bean 이 되려면 @Service 어노테이션을 추가 해주고


서비스의 의존객체 인 @Autowired 어노테이션 추가해줘


여기는 이렇게만 해두고 좀있다가 코딩을 추가 하고


컨트롤러도 있어야 하니 컨트롤러 만들어 주러



컨트롤러 패키지와 클래스 추가해주고



이렇게 만들어 놔줘


컴퍼넌트 스캔이 일어나야 하는 곳을



여기서 설정해줘



* 로 해주면


컴퍼넌트 스캔이 일어나야 하는 곳은 다 해주고

bean 으로 만들고 AutoWired 도 알아서 다 해줘




home.jsp 로 가서



링크 추가


filecontroller 로 가



이런 경로를 가르켜


이 경로대로 jsp 파일 만들어줘




insertform.jsp 코딩 이렇게 해줘


filecontroller 가서



form 에서 name 속성으로 보낸 것이 여기에 들어 오도록 @ModelAttribute 어노테이션을 추가해 준것


( pom.xml 에 commons-io, commons-fileupload 이 두개를 Bean 해논게 있어야지 알아서 해줘 )


fileController 소스코드


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
package com.gura.step06.file.controller;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
 
import com.gura.step06.file.dto.FileDto;
import com.gura.step06.file.service.FileService;
 
@Controller
public class FileController {
    
    //의존객체
    @Autowired
    private FileService fileService;
    
    @RequestMapping("/file/insertform")
    public String insertform(){
        
        return "file/insertform";
    }
    
    @RequestMapping("/file/insert")
    public String insert(HttpServletRequest request,
            @ModelAttribute FileDto dto){
        // FileService 객체를 통해서 업로드 처리를 한다.
        fileService.insert(request, dto);
                
        // 파일 목록보기로 리다일렉트 이동 시킨다.
        return "redirect:/file/list.do";
    }
    
    @RequestMapping("/file/list")
    public ModelAndView list(){
        
        ModelAndView mView = fileService.list();
        mView.setViewName("file/list");
        
        return mView;
    }
    
    @RequestMapping("/file/download")
    public ModelAndView download(@RequestParam int num){
        // 다운로드 할 파일의 정보를 ModelAndView 객체에 담아서 리턴 받는다.
        ModelAndView mView=fileService.getData(num);
        
        // 파일을 다운로드 시켜줄 view 객체의 이름을 지정하고
        mView.setViewName("fileDownView");
        
        // 리턴해 준다.
        return mView;
    }
    
    @RequestMapping("/file/delete")
    public String delete(HttpServletRequest request, @RequestParam int num){
        // FileService 객체를 이용해서 파일 삭제 처리
        fileService.delete(request, num);
        
        return "redirect:/file/list.do";
    }
}
 
 
 
 
 
 
 
Colored by Color Scripter
cs


컨트롤러의 역할


어떤 요청을 받았을때 어떤 서비스를 하고 어떤 곳으로 이동시킬지

하는게 컨트롤러의 역할


request 에 담을게 없으면 ModelAndView 보다는 그냥 문자열로 하는게 나아




fileServiceImpl에도 코딩해 줘야해


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
package com.gura.step06.file.service;
 
import java.io.File;
import java.util.List;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
 
import com.gura.step06.file.dao.FileDao;
import com.gura.step06.file.dto.FileDto;
 
@Service
public class FileServiceImpl implements FileService{
    
    // 의존객체
    @Autowired
    private FileDao fileDao;
    
    @Override
    public void insert(HttpServletRequest request, FileDto dto) {
        //파일을 저장할 폴더의 절대 경로를 얻어온다.
        String realPath=request.getSession()
                .getServletContext().getRealPath("/upload");
        System.out.println(realPath);
        
        //MultipartFile 객체의 참조값 얻어오기
        //FileDto 에 담긴 MultipartFile 객체의 참조값을 얻어온다.
        MultipartFile mFile=dto.getFile();
        //원본 파일명
        String orgFileName=mFile.getOriginalFilename();
        //파일 사이즈
        long fileSize=mFile.getSize();
        //저장할 파일의 상세 경로
        String filePath=realPath+File.separator;
        //디렉토리를 만들 파일 객체 생성
        File file=new File(filePath);
        if(!file.exists()){//디렉토리가 존재하지 않는다면
            file.mkdir();//디렉토리를 만든다.
        }
        //파일 시스템에 저장할 파일명을 만든다. (겹치치 않게)
        String saveFileName=System.currentTimeMillis()+orgFileName;
        try{
            //upload 폴더에 파일을 저장한다.
            mFile.transferTo(new File(filePath+saveFileName));
        }catch(Exception e){
            e.printStackTrace();
        }
        //FileDto 객체에 추가 정보를 담는다.
        dto.setOrgFileName(orgFileName);
        dto.setSaveFileName(saveFileName);
        dto.setFileSize(fileSize);
        //FileDao 객체를 이용해서 DB 에 저장하기
        fileDao.insert(dto);
        
    }
 
    @Override
    public ModelAndView list() {
        // FileDao 를 이용해서 파일 목록을 얻어와서
        List<FileDto> list=fileDao.getList();
        // ModelAndView 객체에 담은다음
        ModelAndView mView = new ModelAndView();
        mView.addObject("list", list);
        // 리턴해준다.
        return mView;
    }
 
    @Override
    public void delete(HttpServletRequest request, int num) {
        // 삭제할 파일의 정보를 얻어온다.
        FileDto dto=fileDao.getData(num);
        // 1. 파일 시스템에서 물리적인 삭제
        String path= request.getServletContext().getRealPath("/upload")+
                File.separator+dto.getSaveFileName();
        try{
            new File(path).delete();
        }catch (Exception e) {}
        // 2. DB 에서 파일 정보 삭제
        fileDao.delete(num);
    }
 
    @Override
    public ModelAndView getData(int num) {
        // 다운로드 시켜줄 파일의 정보를 DB 에서 얻어오고
        FileDto dto=fileDao.getData(num);
        // ModleAndView 객체에 담아서
        ModelAndView mView =new ModelAndView();
        mView.addObject("dto", dto);
        // 리턴해 준다.
        return mView;
    }
 
}
 
Colored by Color Scripter
cs


아까 Dao도 완성시켜 놓았으니 DB관련 된 코드는 다 완성 시킨 것




파일 컨트롤러에서


리다일렉트 이동 시켰으니


그 요청 처리



이제 fileServiceImpl 가서


list 처리


이렇게 list.jsp 만든다음


이렇게 코딩



Quantum DB 플러그인을 설치 해서 board_data 테이블을 깨끗히 만든 다음에


이제 프로젝트 RUN





이렇게 올라 가는 것 확인 가능


다운로드와 삭제도 아까 위에 소스코드 올려준 거에 같이 들어가 있으니


이렇게 링크 보이게 추가만 해주면 프로젝트 완성~


list.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>views/file/list.jsp</title>
</head>
<body>
<h3>업로드 된 파일 목록입니다.</h3>
<table>
    <thead>
        <tr>
            <th>번호</th>
            <th>작성자</th>
            <th>제목</th>
            <th>파일</th>
            <th>크기</th>
            <th>등록일</th>
            <th>삭제</th>
        </tr>
    </thead>
    <tbody>
        <c:forEach var="tmp" items="${list }">
            <tr>
                <td>${tmp.num }</td>
                <td>${tmp.writer }</td>
                <td>${tmp.title }</td>
                <td><a href="download.do?num=${tmp.num }">${tmp.orgFileName }</a></td>
                <td>${tmp.fileSize } <strong>bytes</strong></td>
                <td>${tmp.regdate }</td>
                <td><a href="delete.do?num=${tmp.num }">삭제</a></td>
            </tr>
        </c:forEach>
    </tbody>
</table>
</body>
</html>
Colored by Color Scripter
cs


이제 파일 명을 누르면 다운로드도 받아지고 삭제 링크를 누르면 DB에서 삭제도 됌


끝~~~



반응형

'FrameWork > spring' 카테고리의 다른 글

Spring_Aop_Anno  (0) 2017.07.31
Spring_Aop  (0) 2017.07.31
Step05_JsonResponse-2.회원가입 아이디 중복체크  (0) 2017.07.30
Step05_JSONResponse-1. json01~05  (0) 2017.07.30
Step04_AbstractView-2. 추상뷰  (0) 2017.07.30
'FrameWork/spring' 카테고리의 다른 글
  • Spring_Aop_Anno
  • Spring_Aop
  • Step05_JsonResponse-2.회원가입 아이디 중복체크
  • Step05_JSONResponse-1. json01~05
- 광속거북이 -
- 광속거북이 -
IT관련 일하면서 공부 및 일상 에 관한 내용들을 기록하기 위한 블로그 입니다.
누리IT관련 일하면서 공부 및 일상 에 관한 내용들을 기록하기 위한 블로그 입니다.
- 광속거북이 -
누리
- 광속거북이 -
전체
오늘
어제
  • 카테고리 (453)
    • 구글문서 (4)
    • 설치방법들 (3)
    • FrameWork (73)
      • Django (6)
      • Python (32)
      • AngularJS (13)
      • spring (21)
    • Programing (61)
      • JAVA (11)
      • etc... (2)
      • 오류 해결 (29)
      • Algorithm (5)
    • Front-End (25)
      • CSS (3)
      • html (6)
      • javascript (10)
      • vueJS (5)
    • Back-End (5)
      • 리눅스 (12)
      • PostgreSQL (14)
      • MySQL (2)
      • Shell (1)
      • docker (1)
      • GIT (1)
    • Util (9)
      • BIRT (2)
      • JMeter (3)
      • MobaXterm Personal (1)
      • ClipReport (2)
    • 이클립스 설정 (10)
      • SVN (1)
    • 업무중 기록해둘 것들... (1)
    • 영화 (8)
    • etc.. (198)
      • 여행 (25)
      • 문화생활 (3)
      • tistory (3)
      • 글, 생각 (4)
      • 먹을 곳 (29)
      • issue (4)
      • 결혼 (1)
      • 가족여행기록 (1)
      • Tip (51)
      • 강아지 (5)
      • 일기 (0)
      • 게임 (3)
      • 주식 (7)
      • 코로나19 (7)
      • 맥북 (5)
    • 비공개 (0)

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 합정
  • 설정
  • 이클립스
  • Java
  • tomcat
  • VSCode
  • 맛집
  • 윈도우10
  • 리눅스
  • 설치
  • IntelliJ
  • PostgreSQL
  • 카페
  • 인텔리제이
  • 제주도
  • 포켓몬고
  • 삼성증권
  • 백준
  • 해지
  • 연천

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.1
- 광속거북이 -
Step06_FileUpload
상단으로

티스토리툴바

단축키

내 블로그

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

블로그 게시글

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

모든 영역

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

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