728x90
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if(${!empty msgType}){
$("#messageType").attr("class", "modal-content panel-warning");
$("#myMessage").modal("show");
}
});
</script>
</head>
<body>
<div class="container">
<jsp:include page="../common/header.jsp"/>
<h2>Spring MVC03</h2>
<div class="panel panel-default">
<div class="panel-heading">회원사진등록양식</div>
<div class="panel-body">
<form action="${contextPath}/memImageUpdate.do" method="post" enctype="multipart/form-data">
<input type="hidden" name="memID" value="${mvo.memID}"/>
<table class="table table-bordered" style="text-align: center; border: 1px solid #dddddd;">
<tr>
<td style="width: 110px; vertical-align: middle;">아이디</td>
<td>${mvo.memID}</td>
</tr>
<tr>
<td style="width: 110px; vertical-align: middle;">사진 업로드</td>
<td colspan="2">
<span class="btn btn-default">
이미지를 업로드하세요. <input type="file" name="memProfile"/>
</span>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: left;">
<input type="submit" class="btn btn-primary btn-sm pull-right" value="등록"/>
</td>
</tr>
</table>
</form>
</div>
<!-- 실패 메세지를 출력(modal) -->
<div id="myMessage" class="modal fade" role="dialog" >
<div class="modal-dialog">
<!-- Modal content-->
<div id="messageType" class="modal-content panel-info">
<div class="modal-header panel-heading">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">${msgType}</h4>
</div>
<div class="modal-body">
<p>${msg}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="panel-footer">스프1탄_인프런(박매일)</div>
</div>
</div>
</body>
</html>
가장 중요한건 enctype="multipart/form-data" 속성은 폼 데이터(form data)가 서버로 제출될 때 해당 데이터가 인코딩되는 방법을 명시한다.
<form action="${contextPath}/memImageUpdate.do" method="post" enctype="multipart/form-data">
controller에서 이미지를 처리하는 방법을 알아보자.
여러가지 방법이 있는데 오늘은 고전 방식을 이용해서 업로드 처리를 해본다.
우선 pom.xml에 추가해준다
<!-- https://mvnrepository.com/artifact/com.servlets/cos -->
<dependency>
<groupId>com.servlets</groupId>
<artifactId>cos</artifactId>
<version>09May2002</version>
</dependency>
그리고 controller를 작성해보자
// 회원사진 이미지 업로드(upload, DB저장)
@RequestMapping("/memImageUpdate.do")
public String memImageUpdate(HttpServletRequest request, RedirectAttributes rttr, HttpSession session) {
// 파일 업로드 API(cos.jar, 3가지)
MultipartRequest multi = null;
int fileMaxSize = 10*1024*1024; //10mb
String savePath=request.getRealPath("resources/upload"); //실제 경로를 가져오는 request.getRealPath
try {
// 이미지 업로드
multi = new MultipartRequest(request, savePath, fileMaxSize, "UTF-8", new DefaultFileRenamePolicy()); // request, 경로저장, 사이즈, 한글, 동일이름일때 이름변경
} catch (Exception e) {
e.printStackTrace();
rttr.addFlashAttribute("msgType", "실패 메세지");
rttr.addFlashAttribute("msg", "파일 크기는 10MB를 넘을 수 없습니다");
return "redirect:/memImageForm.do";
}
// 데이터베이스에 회원이미지 업데이트
String memID = multi.getParameter("memID");
String fileName = "";
File file = multi.getFile("memProfile");
String newProfile="";
if(file != null) { // 업로드가 된 상태(.png, .jpg, .gif)
// 이미지 파일 여부를 체크 -> 이미지 파일이 아니면 삭제
String ext = file.getName().substring(file.getName().lastIndexOf(".")+1);
ext = ext.toUpperCase(); // 파일이 대문자이거나 소문자일 수도 있으니까 모든 확장자를 대문자로 변환하고 검사
if(ext.equals("PNG") || ext.equals("GIF") || ext.equals("JPG")) {
// 새로 업로드된 이미지(new), 현재 DB에 있는 이미지(old)
String oldProfile = memberMapper.getMember(memID).getMemProfile();
File oldFile = new File(savePath + "/" + oldProfile);
if(oldFile.exists()) {
oldFile.delete();
}
newProfile = file.getName();
} else { // 이미지파일이 아니면 삭제
if(file.exists()) {
file.delete();
rttr.addFlashAttribute("msgType", "실패 메세지");
rttr.addFlashAttribute("msg", "이미지 파일만 업로드 가능합니다");
return "redirect:/memImageForm.do";
}
}
}
// 새로운 이미지를 테이블에 업데이트
Member mvo = new Member();
mvo.setMemID(memID);
mvo.setMemProfile(newProfile);
memberMapper.memProfileUpdate(mvo); // 이미지 업데이트 성공
Member m = memberMapper.getMember(memID);
// 세션을 새롭게 생성한다.
session.setAttribute("mvo", mvo);
rttr.addFlashAttribute("msgType", "성공 메세지");
rttr.addFlashAttribute("msg", "이미지 변경에 성공했습니다.");
return "redirect:/";
}
728x90
'👩🏫 Study > 스프링레거시 강의' 카테고리의 다른 글
Spring Security설정과 적용하기 (0) | 2023.10.20 |
---|---|
servlet-context.xml, root-context.xml, web.xml 대신 Java로 Configuration하기 (0) | 2023.10.20 |
스프링 로그인/로그아웃 처리하기 (0) | 2023.10.19 |
게시판 회원가입 하기 (0) | 2023.10.19 |
Ajax와 jQuery를 이용한 스프링 게시판 만들기 (0) | 2023.10.19 |