@RequestMapping(value = "databoardDownload.do", method = RequestMethod.GET)

public void databoardDownload(String file, HttpServletRequest request,

        HttpServletResponse response) throws IOException{

     response.setHeader("Content-Disposition", "attachment;filename="+file);

     String fullPath = request.getSession().getServletContext().getRealPath("/resources/upload/databoard/" + file );

      FileInputStream fi = new FileInputStream(fullPath);

      ServletOutputStream sout = response.getOutputStream();

      byte[] buf = new byte[1024];

      int size = 0;

      while((size = fi.read(buf, 0, 1024))!=-1){

         sout.write(buf, 0, size);

      }

      fi.close();

      sout.close();

  

}

'Computer > Spring Maven MyBatis' 카테고리의 다른 글

Spring Mybatis 기본설정  (0) 2014.09.26
Spring 게시판 페이지  (0) 2014.08.18
Spring GET방식 한글 깨짐  (0) 2014.08.18
Spring 파일 업로드  (0) 2014.08.18
Mybatis ResultMap con  (0) 2014.08.13

servlet-context.xml


<aop:config>

<aop:pointcut expression="within(com.kodb.web.*)" id="serviceInsertMethod" />

<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceInsertMethod" />

</aop:config>

<beans:bean name="multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<beans:property name="maxUploadSize" value="10000000" />

</beans:bean>




form.jsp


<div class="table-responsive">

<table class="table table-striped">

<thead>

<tr>

<th class="col-sm-1">번호</th>

<th>제목</th>

<th class="col-sm-2">작성자</th>

<th class="col-sm-2">작성일</th>

</tr>

</thead>

<tbody>

<c:set var="i" value="1"></c:set>

<c:forEach var="a" items="${datalist}">

<tr>

<td>${a.databoard_id }</td>

<td><a data-toggle="collapse" data-parent="#accordion"

href="#collapse${i}">${a.databoard_title }</a></td>

<td>${a.databoard_regname }</td>

<td>${a.databoard_uploaddate }</td>

</tr>




<tr>

<td colspan="4">

<div id="collapse${i}" class="panel-collapse collapse">

<div class="text-right"><a href="databoardDownload.do?file=${a.databoard_filename }" >${a.databoard_filename }</a></div>

<div class="panel-body">${a.databoard_content }</div>

</div>

</td>

</tr>


<c:set var="i" value="${i+1}"></c:set>

</c:forEach>

</tbody>

</table>

</div>




Controller

@RequestMapping(value = "databoardInsert.do", method = RequestMethod.POST)
public String dataupload(HttpServletRequest request,
DataBoardVO dataBoard) {
if (!dataBoard.getFile().isEmpty()) {
        String path = request.getSession().getServletContext().getRealPath("/resources/upload/databoard");
        Date d =  new Date();
        System.out.println(d.getTime());
        String file = d.getTime()+"_"+dataBoard.getFile().getOriginalFilename();
        String fpath = path + "\\" + file;
        System.out.println(fpath);
        FileOutputStream fo= null;
        
        System.out.println(file);
        System.out.println(fpath);
        //나중에 DB에 파일 이름 저장 하려고.
        dataBoard.setDataboard_filename(file);
        
        try {
           fo = new FileOutputStream(fpath);
           fo.write(dataBoard.getFile().getBytes());
           System.out.println("파일저장 완료");

        } catch (FileNotFoundException e) {

           e.printStackTrace();
        } catch (IOException e) {
           
           e.printStackTrace();
        } finally {
           try {
              if(fo!=null)fo.close();
           } catch (IOException e) {
              
              e.printStackTrace();
           }
        }

     }


'Computer > Spring Maven MyBatis' 카테고리의 다른 글

Spring Mybatis 기본설정  (0) 2014.09.26
Spring 게시판 페이지  (0) 2014.08.18
Spring GET방식 한글 깨짐  (0) 2014.08.18
Spring 파일 다운로드  (0) 2014.08.18
Mybatis ResultMap con  (0) 2014.08.13

출처 : http://blog.naver.com/sh_park0107/130175661601


* 화면전환 없이 비동기 업로드 *


1. 파일 업로드 폼

/fileUpload.jsp

 

1
2
3
4

<form name="serverInfoForm" id="serverInfoForm" method="post" action="/serverInfoUpload.do" enctype = "multipart/form-data">

        <input type="file" name="agentInstallFile" id="agentInstallFile"> 

        <input type="submit"  class="btn" value="전송">
</form>

 

  • form 의 id 를 지정해준다.
  • action 을 지정해준다. 파일을 보내는 컨트롤러
  • enctype을 반드시 multipart/form-data로 지정해준다.

 

2jquery.form.js 플러그인 사용하기

 

  • http://malsup.com/jquery/form/#download 에서 jquery.form.js 혹은 jquery.form.min.js 다운을 받아 js폴더에 넣어준다.
  •  <script src="js/jquery.form.js"></script> ㅎㅔ더(<HEAD></HEAD>에 삽입해준다

 

 

3. 파일업로드 jquery 소스 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$('#serverInfoForm').ajaxForm({
        
        dataType : 'text', 
        beforeSerialize: function(){
             // form을 직렬화하기전 엘레먼트의 속성을 수정할 수도 있다.            
        },
        beforeSubmit : function() {
        //action에 걸어주었던 링크로 가기전에 실행 ex)로딩중 표시를 넣을수도 있다.
        },

        success : function(data) {
             //컨트롤러 실행 후 성공시 넘어옴
            alert("등록완료 ! ");            
        }

    });

http://malsup.com/jquery/form/ 참고 ! (API)

 

 

  • form id를 넣어준다. $("#serverInfoForm")
  • beforeSerialize 는 form 을 직렬화 하기전에 실행되는 함수이다.
  • beforeSubmit 는 form 이 submit 되기전에 실행되는 함수

 

4. 파일업로드 컨트롤러 

MultipartHttpServletRequest 를 사용하기위 엮인글의 1번과, 3번 설정 필요!!

역인글 :  http://blog.naver.com/sh_park0107/130175605306


/serverInfoUpload.do

 Colored By Color Scripter

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
@RequestMapping("/serverInfoUpload.do")
    public ModelAndView mybatistest(HttpServletRequest request) throws IOException{

        ModelAndView mav = new ModelAndView();
        
        MultipartHttpServletRequest multi = (MultipartHttpServletRequest) request;
        MultipartFile file = multi.getFile("agentInstallFile");//jsp 페이지에서 input type="file"의 파라미터명
                
         String path="";
         UUID randomeUUID = UUID.randomUUID();//중복 파일명 방지
                  
         if(file!=null){
        
          System.out.println("파라미터명" + file.getName());
          System.out.println("파일크기" + file.getSize());
          System.out.println("파일 존재" + file.isEmpty());
          System.out.println("오리지날 파일 이름" + file.getOriginalFilename());
        
          
          path = "d:/upload/";
          InputStream inputStream = null;
          OutputStream outputStream = null;
          
          String organizedfilePath="";
          
          try {
              
 
              if (file.getSize() > 0) {
                  inputStream = file.getInputStream();
                  File realUploadDir = new File(path);
                  
                  if (!realUploadDir.exists()) {//업로드하려는 path에 폴더가 없을경우
                      realUploadDir.mkdirs();//폴더생성.
                  }
                  
                  
                  organizedfilePath = path + randomeUUID + "_" + file.getOriginalFilename();
                  System.out.println(organizedfilePath);//파일이 저장된경로 + 파일 명
                  
                  outputStream = new FileOutputStream(organizedfilePath);
 
                  int readByte = 0;
                  byte[] buffer = new byte[8192];
 
                  while ((readByte = inputStream.read(buffer, 0, 8120)) != -1) {
                      outputStream.write(buffer, 0, readByte); //파일 생성 ! 
                      
                  }
            
                  
              }
              
          } catch (Exception e) {
              // TODO: handle exception
              e.printStackTrace();
 
          } finally {
 
              outputStream.close();
              inputStream.close();
          }
          
      
                 
         }    
          mav.setViewName("fileUpload");
        return mav;
                
    }

 


'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

JSP SQL Injection 방어 기법  (0) 2014.08.21
JSP 버튼이벤트  (0) 2014.08.19
JSP Modal 사용하기  (0) 2014.08.14
JSP c:choose  (0) 2014.08.14
JSP select onchange  (0) 2014.08.14

#{category:VARCHAR}   처리하면 된다   


<insert id="insertDataboard" parameterType="databoardvo">

      insert into 

      databoard (............., category)

      values (............., #{category:VARCHAR})

   </insert>



'Computer > JAVA' 카테고리의 다른 글

Java PrimeNumber  (0) 2014.08.29
Java 최대공약수  (0) 2014.08.29
JDBC Date형 처리  (0) 2014.08.14
Java util.date sql.date 형변환  (1) 2014.08.14
Java ArrayList 추가  (0) 2014.08.13

<c:set var="rec" value="resources/"></c:set>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>My Lectures</title>




</head>

<body>


<a href="databoardInsert.do" data-toggle="modal" data-target="#dataModal" class="btn btn-success pull-right">글쓰기</a>

    <!-- Modal -->

<div class="modal fade" id="dataModal" tabindex="-1" role="dialog" aria-labelledby="dataModalLabel" aria-hidden="true" >

  <div class="modal-dialog modal-sm">

    <div class="modal-content" >

      <div class="modal-header">

        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>

        <h4 class="modal-title" id="dataModalLabel">Modal title</h4>

      </div>

      <div class="modal-body" >

        ....

      </div>

      <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="button" class="btn btn-primary">Save changes</button>

      </div>

    </div>

  </div>

</div> 



</body>

</html>



form


<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<div class="modal-header">

<button type="button" class="close" data-dismiss="modal">

<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>

</button>

<h4 class="modal-title" id="loginModalLabel">자료 올리기</h4>

</div>

<div class="modal-body" >


<form action="databoardInsert.do" method="post">

<div class="row row-form">


<label for="title" class="col-sm-2">  제목</label>

<div class="col-sm-10">

<input type="text" class="form-control" id="title"

placeholder="제목을 입력하세요">

</div>

</div>

<div class="row row-form">

<label for="filedirectory" class="col-sm-2">파일 첨부</label>

<div class="col-sm-10">

<input type="text" class="form-control" id="filedirectory"

placeholder="파일 경로">

</div>

</div>

<div class="row row-form">

<label for="content" class="col-sm-2">내용</label>

<div class="col-sm-10">

<textarea class="form-control" id="content" rows="7"></textarea>

</div>

</div>

<div class="row row-form">

<label for="content" class="col-sm-2">파일선택</label>

<div class="col-sm-10">

<input type="file" id="attachment1" name="attachment1"

placeholder="사진첨부1" class="input-large" required>

</div>

</div>

<div class="row row-form">

<div class="col-sm-12">

<button type="submit" class="btn btn-lg btn-primary pull-right">등록</button>

</div>

</div>




</form>

</div>



'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

JSP SQL Injection 방어 기법  (0) 2014.08.21
JSP 버튼이벤트  (0) 2014.08.19
JQUERY 화면전환 없이 비동기 업로드  (0) 2014.08.18
JSP c:choose  (0) 2014.08.14
JSP select onchange  (0) 2014.08.14

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


<c:choose>

<c:when test="${b.att_checks==0 }">결석</c:when>

<c:when test="${b.att_checks==1 }">출석</c:when>

<c:when test="${b.att_checks==2 }">지각</c:when>

<c:when test="${b.att_checks==3 }">조퇴</c:when>

</c:choose>

'Computer > JSP Servlet JavaScript' 카테고리의 다른 글

JSP SQL Injection 방어 기법  (0) 2014.08.21
JSP 버튼이벤트  (0) 2014.08.19
JQUERY 화면전환 없이 비동기 업로드  (0) 2014.08.18
JSP Modal 사용하기  (0) 2014.08.14
JSP select onchange  (0) 2014.08.14

MVC 모델에서 Util.date 를 받아 올때 형변환처리를 해주면 된다.


public void setAtt_date(Date att_date) {

java.sql.Date d2 = new java.sql.Date(att_date.getTime());

System.out.println(d2);


this.att_date = d2;

}

'Computer > JAVA' 카테고리의 다른 글

Java 최대공약수  (0) 2014.08.29
JDBC Null값 처리  (0) 2014.08.18
Java util.date sql.date 형변환  (1) 2014.08.14
Java ArrayList 추가  (0) 2014.08.13
Java 확장 For 문  (0) 2014.08.13

Date d = new Date();

System.out.println(d);

java.sql.Date d2 = new java.sql.Date(d.getTime());

System.out.println(d2);





'Computer > JAVA' 카테고리의 다른 글

JDBC Null값 처리  (0) 2014.08.18
JDBC Date형 처리  (0) 2014.08.14
Java ArrayList 추가  (0) 2014.08.13
Java 확장 For 문  (0) 2014.08.13
Java HashMap  (0) 2014.08.13

http://codelion.net/

'Computer > Link..' 카테고리의 다른 글

안드로이드 UI참고 JOA Soft  (0) 2014.08.29
부트스트렙  (0) 2014.08.29
프로그래밍 입문용 개발툴 HelloWorld  (0) 2014.08.14
안드로이드 Unity 게임만들기  (0) 2014.08.14
Unity3D Korea  (0) 2014.08.14

http://ryulib.tistory.com/m/post/327

'Computer > Link..' 카테고리의 다른 글

부트스트렙  (0) 2014.08.29
CodeLion 웹서비스 만들기  (0) 2014.08.14
안드로이드 Unity 게임만들기  (0) 2014.08.14
Unity3D Korea  (0) 2014.08.14
Unity3D 기초강의  (0) 2014.08.14

+ Recent posts