커뮤니티 - 프로필 수정, 미리보기 기능 (23.07.24)

·2023년 7월 24일
0

Server

목록 보기
29/35
post-thumbnail

📝 프로필 수정 미리보기 기능


💡 VS Code

🔎 myPage-profile.jsp

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

<%-- 문자열 관련 함수(메소드) 제공 JSTL (EL 형식으로 작성) --%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Page</title>

    <link rel="stylesheet" href="${contextPath}/resources/css/main-style.css">

    <link rel="stylesheet" href="${contextPath}/resources/css/myPage-style.css">
    
    <script src="https://kit.fontawesome.com/4dca1921b4.js" crossorigin="anonymous"></script>

</head>
<body>

    <main>
		
		<jsp:include page="/WEB-INF/views/common/header.jsp"/>
		
        <!-- 마이페이지 - 내 정보 -->
        <section class="myPage-content">

			<!-- 사이드메뉴 include  -->
			<jsp:include page="/WEB-INF/views/member/sideMenu.jsp"/>

            <!-- 오른쪽 마이페이지 주요 내용 부분 -->
            <section class="myPage-main">

                <h1 class="myPage-title">프로필</h1>
                <span class="myPage-explanation">프로필 이미지를 변경할 수 있습니다.</span>

                <form action="#" method="POST" name="myPage-form">

                    <div class="profile-image-area">
                        <img src="${contextPath}/resources/images/user.png" id="profile-image">
                    </div>

                    <div class="profile-btn-area">
                        <label for="input-image">이미지 선택</label>
                        <input type="file" name="profileImage" id="input-image">
                        <button type="submit">변경하기</button>
                    </div>

                    <div class="myPage-row">
                        <label>이메일</label>
                        <span>${loginMember.memberEmail}</span>
                    </div>

                    <div class="myPage-row">
                        <label>가입일</label>
                        <span>${loginMember.enrollDate}</span>
                    </div>

                </form>

            </section>

        </section>

    </main>

	<jsp:include page="/WEB-INF/views/common/footer.jsp"/>

    <!-- myPage.js 추가 -->
    <script src="${contextPath}/resources/js/member/myPage.js"></script>
</body>
</html>

🔎 myPage-style.css

...
/* 프로필 */

/* 프로필 이미지 영역 */
.profile-image-area{
    width: 150px;
    height: 150px;
    border: 3px solid #ddd;
    border-radius: 50%;

    display: flex;
    justify-content: center;
    align-items: center;

    position: relative;
}

/* 프로필 이미지 */
#profile-image{
    width: 100%;
    height: 100%;
    border-radius: 50%;
}

/* 프로필 버튼 영역 */
.profile-btn-area{
    width: 230px;
    margin: 20px 0;
    display: flex;
    align-items: center;
    justify-content: space-around;
}

/* 프로필 버튼 영역의 모든 자식 요소 */
.profile-btn-area > *{
    width: 110px;
    height: 33px;

    padding: 5px 10px;
    border: 1px solid black;
    background-color: white;
    font-size: 14px;
    cursor: pointer;
    text-align: center;
}

/* 파일 선택 버튼 */
#input-image{
    display: none;
}

/* 변경하기 버튼 */
.profile-btn-area > button{
    background-color: #455ba8;
    color: white;
    border: 0;
}

🔎 index.jsp

...
            		<%-- 로그인이 되어 있는 경우 --%>
            		<c:otherwise>
            			<article class='login-area'>
            			
            				<!-- 회원 프로필 이미지 -->
            				<a href="${contextPath}/member/myPage/profile">
            					<img src="/community/resources/images/user.png" id="member-profile">
            				</a>

...

🔎 sideMenu.jsp

...
<!-- 왼쪽 사이드 메뉴 -->
<section class="left-side">
    사이드 메뉴

    <ul class="list-group">
        <!-- /community/member/myPage/profile -->        
        <li> <a href="${contextPath}/member/myPage/profile">프로필</a> </li>
...

🔎 myPage.js

// 회원 프로필 이미지 변경(미리보기)
const inputImage = document.getElementById("input-image");

if(inputImage != null){ // inputImage 요소가 화면에 존재할 때

    // input type="file" 요소는 파일이 선택될 때 change 이벤트가 발생한다.
    inputImage.addEventListener("change", function(){
        
        // this : 이벤트가 발생한 요소(input type="file")
        
        // files : input type="file"만 사용 가능한 속성으로
        //         선택된 파일 목록(배열)을 반환
        // console.log(this.files);
        // console.log(this.files[0]); // 파일 목록에서 첫 번째 파일 객체를 선택

        if(this.files[0] != undefined){ // 파일이 선택되었을 때

            const reader = new FileReader();
            // 자바스크립트의 FileReader
            // - 웹 애플리케이션이 비동기적으로 데이터를 읽기 위하여 사용하는 객체

            reader.readAsDataURL(this.files[0]);
            // FileReader.readAsDataURL(파일)
            // - 지정된 파일의 내용을 읽기 시작함
            // - 읽어오는 게 완료되면 result 속성 data:에
            //   읽어온 파일의 위치를 나타내는 URL이 포함됨
            // -> 해당 URL을 이용해서 브라우저에 이미지를 볼 수 있다.

            // FileReader.onload = function(){}
            //  - FileReader가 파일을 다 읽어온 경우 함수를 수행
            reader.onload = function(e){ // 고전 이벤트 모델
                // e : 이벤트 발생 객체
                // e.target : 이벤트가 발생한 요소 -> FileReader
                // e.target.result : FileReader가 읽어온 파일의 URL

                // 프로필 이미지에 src 속성의 값을 FileReader가 읽어온 파일을 URL로 변경
                const profileImage = document.getElementById("profile-image");

                profileImage.setAttribute("src", e.target.result);
                // -> setAttribute() 호출 시 중복되는 속성이 존재하면 덮어쓰기
            }
        }
    });
}
profile
풀스택 개발자 기록집 📁

0개의 댓글