본문 바로가기
Spring

75일차//spring/ Tiles를 활용한 게시판만들기 _5(자료실, 파일 업로드) 💾MultipartFile

by aesup 2021. 4. 25.
728x90

추후 참고할 사이트 

이미지 업로드 (Spring+Ajax) (aejeong.com)

 

자료실

PdsDto

package bit.com.a.dto;

import java.io.Serializable;

// PDS - Public Domain Software = 자료실
public class PdsDto implements Serializable {

	private int seq;
	private String id;
	
	private String title;
	private String content;	
	private String filename;  //시용자가 올린 기존파일이름
	private String newFilename; //DB저장시 중복을 피하기위해 업로드날짜로 변경할 파일이름
	
	private int readcount; //조회수
	private int downcount;	//다운로드수
	private String regdate; //게시물 입력한 날짜
	
	
	public PdsDto() {
	}	

	public PdsDto(int seq, String id, String title, String content, String filename, String newFilename, int readcount,
			int downcount, String regdate) {
		super();
		this.seq = seq;
		this.id = id;
		this.title = title;
		this.content = content;
		this.filename = filename;
		this.newFilename = newFilename;
		this.readcount = readcount;
		this.downcount = downcount;
		this.regdate = regdate;
	}

	public PdsDto(String id, String title, String content, String filename, String newFilename) {
		super();
		this.id = id;
		this.title = title;
		this.content = content;
		this.filename = filename;
		this.newFilename = newFilename;
	}

	public int getSeq() {
		return seq;
	}

	public void setSeq(int seq) {
		this.seq = seq;
	}

	public String getId() {
		return id;
	}

	```

 

Pdslist.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<table class="list_table" style="width: 85%">
<colgroup>
	<col width="50"><col width="100"><col width="300"><col width="50">
	<col width="50"><col width="50"><col width="100"><col width="50">
</colgroup>

<thead>
<tr>
	<th>번호</th><th>작성자</th><th>제목</th><th>다운로드</th>
	<th>조회수</th><th>다운수</th><th>작성일</th><th>삭제</th>
</tr>
</thead>

<tbody>

<c:forEach var="pds" items="${pdslist }" varStatus="i">

<tr>
	<th>${i.count }</th>
	<td>${pds.id }</td>
	<td style="text-align: left;">
		<a href="pdsdetail.do?seq=${pds.seq }">
			${pds.title }
		</a>
	</td>
	<td>
		<input type="button" name="btnDown" value="다운로드"
			onclick="filedown('${pds.filename}','${pds.newFilename}', '${pds.seq }')">		
	</td>
	<td>${pds.readcount }</td>
	<td>${pds.downcount }</td>
	<td>
		<font size="1">${pds.regdate }</font>
	</td>
	<td>
		<img alt="" src="image/del.png" data_file_seq="${pds.seq }" class="btn_fileDelete">
	</td>
</tr>
</c:forEach>
</tbody>
</table>


<br><br>
<!--페이징  -->
<div class="container">
	<nav aria-label="Page navigation">
		<ul class="pagination" id="pagination" style="justify-content:center;"></ul>
	</nav>
</div>

<br><br>
<!-- 자료추가 버튼 -->
<div id="button.wrap">
	<span class="button blue">
		<button type="button" id="_btnAdd">자료추가</button>
	</span>
</div>



<!-- 다운로드 버튼을 클릭시 -->
<form name="file_Down" action="fileDownload.do" method="post">
	<input type="hidden" name="newFilename">
	<input type="hidden" name="filename">
	<input type="hidden" name="seq">
</form>






<script>

getBbsListCount();


$("#_btnAdd").click(function () {
	location.href = "pdswrite.do";
});

function filedown(filename, newFilename, seq) {
	
	alert("다운로드 합니다");
	let doc = document.file_Down;
	
	doc.filename.value = filename;
	doc.newFilename.value = newFilename;
	doc.seq.value = seq;
	
	
	
	doc.submit();
}





//paging 처리
function loadPage( totalCount ) {

	let pageSize = 10;
	let nowPage = 1;
	
	let _totalPages = totalCount / pageSize;
	if(totalCount % pageSize > 0){
		_totalPages++;
	}
	
	$("#pagination").twbsPagination('destroy');	// 페이지 갱신 : 페이징을 갱신해 줘야 번호가 재설정된다.

	$("#pagination").twbsPagination({
	//	startPage: 1,
		totalPages: _totalPages,
		visiblePages: 10,
		first:'<span sria-hidden="true">«</span>',
		prev:"이전",
		next:"다음",
		last:'<span sria-hidden="true">»</span>',
		initiateStartPageClick:false,		// onPageClick 자동 실행되지 않도록 한다
		onPageClick:function(event, page){
			nowPage = page;
		//	alert('nowPage:' + page);
			getBbsListData( page - 1 );
		}
	});	
}



//글의 총수를 취득
function getBbsListCount() {
	
	$.ajax({
		url:"./pdscount.do",
		type:"get",
		data:{ page:0 },
		success:function( count ){
		//	alert('success');
		//	alert(count);
			loadPage(count);
		},
		error:function(){
			alert('error');
		}		
	});
}


</script>




PdsController

@Controller
public class PdsController {

	
	@Autowired
	PdsService service;
	
	
	  @RequestMapping(value="pdslist.do", method = {RequestMethod.GET,RequestMethod.POST})
	  public String pdslist(Model model) {
		  
		  model.addAttribute("doc_title", "자료실목록");
		  
		  List<PdsDto> list = service.getPdsList();
		  model.addAttribute("pdslist", list);
		  
		  return "pdslist.tiles";
		  
	  }

자료 업로드

pdswrite.jsp

 

-제목, 내용 미입력시 글작성 불가능(script)

-input type "file"로 파일업로드 가능

-enctype="multipart/form-data" 전송

 

multipart/form-data는 파일 업로드가 있는 양식요소에 사용되는 enctype 속성의 값중 하나이고, multipart는 폼데이터가 여러 부분으로 나뉘어 서버로 전송되는 것을 의미합니다.

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


<form name="frmFrom" id="_frmForm" action="pdsupload.do" method="post"
	enctype="multipart/form-data">
	
	<table class="list_table">
		<tr>
			<th>아이디</th>
			<td>
				<input type="text" name="id" readonly="readonly" value="${login.id} " size="50">
			</td>
		</tr>
		
		<tr>
				
				<th>제목</th>
				<td>
					<input id="_title" type="text" name="title"  size="50">
				</td>
				
		
		</tr>
		<tr>
				
				<th>파일 업로드</th>
				<td>
					<input type="file" name="fileload"  size="50">
				</td>
				
		
		</tr>
		<tr>
				
				<th>내용</th>
				<td>
					<textarea id="_content" rows="10" cols="50" name="content"></textarea>
				</td>
				
		
		</tr>
		
		<tr>
				
				
				<td colspan="2" style="height: 50px; text-align: center">
					<a href="#none" id="_btnPds">
						<img alt="" src="image/bwrite.png">
					</a>
				</td>
				
		
		</tr>
		
		
		
	</table>
</form>

<script type="text/javascript">

$("#_btnPds").click(function () {
	
	if( $("#_title").val().trim() == "" ){
		alert("제목을 입력해 주세요");
		$("#_title").focus();
	}else if($("#_content").val().trim() == ""){
		alert("내용을 입력해 주세요");
		$("#_content").focus();
	}else{
		$(_frmForm).submit();
		
	}
	
});


</script>


글쓰기 버튼 누를시 controller이동

 

MultipartFile을 사용한 File 업로드

(multipart/form-data)

 

 

SpringFramework환경의 서버라면 SpringFramework에서 제공하고 있는 MultipartFile 클래스와 MultipartHttpServletRequest 클래스를 사용해서 File 업로드 기능을 구현할 수 있습니다

이 두가지 클래스를 사용해서 어떻게 File 업로드 기능이 구현될 수 있는지 Controller로 들어오는 요청 파라미터의 타입을 기준으로 보겠습니다.

참고로 제가 짠 코드는 FIle 업로드 방식으로 클라이언트에서 서버로 HTTP 요청을 할 때, “Content-Type” 필드의 내용을 “multipart/form-data”로 세팅해서 요청해야 합니다.

 

아래와 같이 컨트롤러에서 데이터를 받아줬을때

DB파일이름이 중복되어 업로드 되는것을 막아주기위해 파일명을 변경해주는 함수 사용

package bit.com.a.utilex;

import java.util.Date;

public class PdsUtil {
	//파일명 -> 변경(time)
	
	//myfile.txt - > f.indexOf('.') - >
	//파일명, 확장자명
	//f.substring(6) -> .txt
	
	
	
	public static String getNewFileName(String f) {
		String filename = "";
		String fpost = "";
		
		if(f.indexOf('.')>0) {
			//indexOf 지정된 요소를 찾는다
			
			fpost = f.substring(f.indexOf('.')); 
			//.의 위치부터 끝까지 자른다
			
			
			
			System.out.println("fpost" + fpost);
			
			filename = new Date().getTime() + fpost;
					
		}else {
			filename = new Date().getTime() + ".back";
		}
		
		return filename;
	}
	
}

PdsController

 @RequetParam MultipartFile 타입을 사용하는 방법

요청파라미터 타입을 @RequestParam 어노테이션과 함께 사용하는 경우입니다. 이 경우, 서버는 클라이언트의 HTTP 요청 메시지에 포함된 파라미터들을 모두 분리해서 컨트롤할 수 있기 때문에, 컨트롤러의 요청파라미터 타입 중 MultipartFile타입에 해당하는 한가지를 직접 골라서, file 데이터를 직접 다룰 수 있다는 장점이 있지만, file 데이터 외에 다른 파라미터들(ex, String, Integer, MultipartFile)을 몇가지 추가해서 함께 받는다면 코드가 조금 지저분해질 수도 있다는 단점이 있습니다.

 

file.getOriginalFilename() : 클라이언트가 업로드한 파일 원본 이름

 

req.getServletContext().getRealPath().getContextPath("/upload")

파일 업로드 시 프로젝트 내부 폴더를 이용하기 위해서 상대 경로를 가지고 왔다.

 @RequestMapping(value = "pdsupload.do", method = {RequestMethod.GET, RequestMethod.POST})
		public String pdsupload(PdsDto pdsdto, 
							@RequestParam(value = "fileload", required = false)
							MultipartFile fileload, 
							HttpServletRequest req) {
			
			// filename 취득
			String filename = fileload.getOriginalFilename();
			pdsdto.setFilename(filename);	// 원본 파일명을 설정
			
			// upload 경로 설정
			// server(tomcat)
			String fupload = req.getServletContext().getRealPath("/upload");
			
			// 폴더
			// String fupload = "d:\\tmp";
			
			System.out.println("fupload:" + fupload);
			
			// 파일명 변경 처리
			String newfilename = PdsUtil.getNewFileName(pdsdto.getFilename());		
			pdsdto.setNewFilename(newfilename);
			
			File file = new File(fupload + "/" + newfilename); 
			
			try {
				// 실제로 업로드 되는 부분
				FileUtils.writeByteArrayToFile(file, fileload.getBytes());
				
				// db에 저장
				service.uploadPds(pdsdto);
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return "redirect:/pdslist.do";
		}

 

 

 

728x90