• 티스토리 홈
  • 프로필사진
    Song hyun
  • 방명록
  • 공지사항
  • 태그
  • 블로그 관리
  • 글 작성
Song hyun
  • 프로필사진
    Song hyun
    • 분류 전체보기 (780)
      • 백준 (0)
      • 영어 (2)
        • Diary (0)
        • Toast Masters (2)
      • 메모 (13)
      • 설치 메뉴얼 (30)
      • Java (178)
      • MySQL (60)
      • JSP (67)
      • Springboot (46)
      • HTML,CSS, JS (71)
        • HTML (8)
        • CSS (12)
        • JavaScript (37)
        • HTML&CSS 스터디 (13)
      • C++ (7)
      • Linux (7)
      • JPA (34)
      • Kotlin (2)
      • Flutter (42)
      • Error Note (39)
      • 디자인 패턴 (12)
      • 디지털논리회로 (4)
      • 데이터베이스 시스템 (8)
      • 알고리즘 (7)
      • 운영체제 (3)
      • 이산수학 (3)
      • 인공지능 (1)
      • 자료 구조 (14)
        • 기본 개념 (14)
        • 자료구조 스터디 (0)
      • 💡My project (76)
        • 팩맨 : Java Swing 게임 제작 프로젝트 (6)
        • 네이트톡 : Java 소켓 통신 프로젝트 (4)
        • 포켓옥션 : HikariCP&JDBC CRUD 프.. (3)
        • 이지 부산 : BDIA-Devton 2024 프로.. (20)
        • 그린 유니버시티 : JSP를 사용한 학사관리 프로.. (1)
        • 애드 포커 : 웹 소켓과 Spring을 사용한 카.. (1)
        • 셸위 : 게임 친구 매칭 사이트 (21)
        • 다모아 : 개발자 중개 플랫폼 (20)
      • 📗스터디 (13)
        • CNN : 웹개발 스터디 (10)
        • Node&React로 유튜브 사이트 만들기 (3)
      • 📙독서 및 강연 기록 (36)
        • 강연 (14)
        • 독서 (22)
  • 방문자 수
    • 전체:
    • 오늘:
    • 어제:
  • 최근 댓글
      등록된 댓글이 없습니다.
    • 최근 공지
        등록된 공지가 없습니다.
      # Home
      # 공지사항
      #
      # 태그
      # 검색결과
      # 방명록
      • [Springboot] 34. 파일 업로드(2단계-DTO, Service, JSP 수정)
        2024년 08월 13일
        • Song hyun
        • 작성자
        • 2024.08.13.:19
        728x90
        반응형

        [Springboot] 34. 파일 업로드(2단계-DTO, Service, JSP 수정)

         

        1. signUpDTO.java

        package com.tenco.bank.dto;
        
        import org.springframework.web.multipart.MultipartFile;
        
        import com.tenco.bank.repository.model.User;
        
        import lombok.AllArgsConstructor;
        import lombok.Builder;
        import lombok.Data;
        import lombok.NoArgsConstructor;
        import lombok.ToString;
        
        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        @Builder
        @ToString
        public class SignUpDTO {
        	
        	private String username; 
        	private String password; 
        	private String fullname;
        	private MultipartFile mFile;
        	private String originFileName;
        	private String uploadFileName;
        	
        	
        	// 2단계 로직 - User Object 반환 
        	public User toUser() {
        		return User.builder()
        				.username(this.username)
        				.password(this.password)
        				.fullname(this.fullname)
        				.originFileName(this.originFileName)
        				.uploadFileName(this.uploadFileName)
        				.build();
        	} 
        	
        	
        }

         

         

        2. UserService.java - createUser()

        	/**
        	 * 회원 등록 서비스 기능
        	 * 트랜잭션 처리  
        	 * @param dto
        	 */
        	@Transactional // 트랜잭션 처리는 반드시 습관화 
        	public void createUser(SignUpDTO dto) {
        		int result = 0; 
        		
        		System.out.println(dto.getMFile().getOriginalFilename());
        		
        		if(!dto.getMFile().isEmpty()) {
        			// 파일 업로드 로직 구현
        			String[] fileNames = uploadFile(dto.getMFile());
        			
        			dto.setOriginFileName("aaaa.png");
        			dto.setUploadFileName("1234_aaaa.png");
        		}
        		
        		
        		try {
        			// 코드 추가 부분
        			// 회원 가입 요청 시, 사용자가 던진 비밀번호 값을 암호화처리 해야함
        			String hashpwd = passwordEncoder.encode(dto.getPassword());
        			System.out.println("암호화 확인: "+hashpwd);
        			//dto.setPassword(hashpwd);
        			//result = userRepository.insert(dto.toUser());
        		} catch (DataAccessException e) {
        			throw new DataDeliveryException("중복 이름을 사용할 수 없습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
        		} catch (Exception e) {
        			throw new RedirectException("알 수 없는 오류", HttpStatus.SERVICE_UNAVAILABLE);
        		}
        		if(result != 1) {
        			throw new DataDeliveryException("회원가입 실패", HttpStatus.INTERNAL_SERVER_ERROR);
        		}
        	}

         

         

        3. User 클래스 & User.xml

        package com.tenco.bank.repository.model;
        
        import java.sql.Timestamp;
        
        import lombok.AllArgsConstructor;
        import lombok.Builder;
        import lombok.Data;
        import lombok.NoArgsConstructor;
        import lombok.ToString;
        
        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        @Builder
        @ToString
        public class User {
        	private Integer id; 
        	private String username; 
        	private String password; 
        	private String fullname; 
        	private String originFileName;
        	private String uploadFileName;
        	private Timestamp createdAt;
        }
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        <mapper namespace="com.tenco.bank.repository.interfaces.UserRepository">
        	
        	<!-- 반드시 세미콜론을 제거 해야 한다.   -->
        	<!-- id는 매칭되어 있는 인터페이스에 메서드 명과 같아야 한다.  -->	
        	<insert id="insert">
        		insert into user_tb(username, password, fullname, origin_file_name, upload_file_name ) 
        		values( #{username}, #{password}, #{fullname}, #{originFileName}, #{uploadFileName})
        	</insert>
        	
        	<update id="updateById">
        		update user_tb set username = #{username}, 
        		                   password = #{password}, 
        		                   fullname = #{fullname},
        		                   where id = #{id} 
        	</update>
        	
        	<delete id="deleteById">
        		delete from user_tb where id = #{id}
        	</delete>
        	
        	<select id="findById" resultType="com.tenco.bank.repository.model.User">
        		select * from user_tb where id = #{id}
        	</select>
        	
        	<select id="findAll" resultType="com.tenco.bank.repository.model.User">
        		select * from user_tb
        	</select>
        	
        	<select id="findByUsernameAndPassword" resultType="com.tenco.bank.repository.model.User" >
        		select * from user_tb where username = #{username} and password = #{password}	
        	</select>
        	
        	<select id="findByUsername" resultType="com.tenco.bank.repository.model.User" >
        		select * from user_tb where username = #{username}
        	</select>
        	
        </mapper>
        select*from user_tb;
        
        alter table user_tb
        add column origin_file_name varchar(200);
        
        alter table user_tb
        add column upload_file_name varchar(200);

         

         

        4. signUp.jsp

        <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
        
        <!-- header.jsp  -->
        <%@ include file="/WEB-INF/view/layout/header.jsp"%>
        
        <!-- start of content.jsp(xxx.jsp)   -->
        <div class="col-sm-8">
        	<h2>회원 가입</h2>
        	<h5>Bank App에 오신걸 환영합니다</h5>
        	
        	<form action="/user/sign-up" method="post" enctype="multipart/form-data"> 
        		<div class="form-group">
        			<label for="username">username:</label>
        			<input type="text" class="form-control" placeholder="Enter username" id="username" name="username" value="야스오1"  >
        		</div>
        		<div class="form-group">
        			<label for="pwd">Password:</label>
        			<input type="password" class="form-control" placeholder="Enter password" id="pwd" name="password" value="asd123">
        		</div>
        		<div class="form-group">
        			<label for="fullname">fullname:</label>
        			<input type="text" class="form-control" placeholder="Enter fullname" id="fullname" name="fullname" value="바람검객">
        		</div>
        		 <div class="custom-file">
            	  <input type="file" class="custom-file-input" id="customFile" name="mFile">
              	  <label class="custom-file-label" for="customFile">Choose file</label>
             	</div>
        		<div class="d-flex justify-content-end">
        			<button type="submit" class="btn btn-primary mt-md-4">회원가입</button>
        		</div>
        	</form>
        
        
        </div>
        <!-- end of col-sm-8  -->
        </div>
        </div>
        <!-- end of content.jsp(xxx.jsp)   -->
        
        <script>
        // Add the following code if you want the name of the file appear on select
        $(".custom-file-input").on("change", function() {
          var fileName = $(this).val().split("\\").pop();
          $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
        });
        </script>
        
        <!-- footer.jsp  -->
        <%@ include file="/WEB-INF/view/layout/footer.jsp"%>

         

         

        *5. 파일 업로드 메서드 - uploadFile()

        private String[] uploadFile(MultipartFile mFile) {
        		// 파일 업로드 구현
        		
        		// 파일 용량 체크
        		if(mFile.getSize() > Define.MAX_FILE_SIZE) {
        			throw new DataDeliveryException("파일 크기는 20MB보다 클 수 없습니다.", HttpStatus.BAD_REQUEST);
        		}
        		
        		// 서버 컴퓨터에 파일을 넣을 디렉토리가 있는지 검사
        		String saveDirectory = Define.UPLOAD_FILE_DERECTORY;
        		File directory = new File(saveDirectory);
        		if(!directory.exists()) {
        			directory.mkdirs();
        		}
        		
        		// 파일 이름 생성 (파일명 중복 예방)
        		String uploadFileName = UUID.randomUUID()+"_"+mFile.getOriginalFilename();
        		
        		// 파일 전체 경로 + 새로 생성한 파일명
        		String uploadPath = saveDirectory+uploadFileName;
        		File destination = new File(uploadPath);
        		
        		// 반드시 수행
        		try {
        			mFile.transferTo(destination);
        		} catch (IllegalStateException | IOException e) {
        			e.printStackTrace();
        			throw new DataDeliveryException("파일 업로드 중에 오류가 발생했습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
        		}
        		
        		return new String[] {mFile.getOriginalFilename(), uploadFileName};
        	}
        	/**
        	 * 서버 운영체제에 파일 업로드 기능
        	 * MultipartFile etOriginFilename : 사용자가 작성한 파일 명
        	 * uploadFileName : 서버 컴퓨터에 저장될 파일명
        	 * @param mFile
        	 * @return
        	 */
        	private String[] uploadFile(MultipartFile mFile) {
        		// 파일 업로드 구현
        		
        		// 파일 용량 체크
        		if(mFile.getSize() > Define.MAX_FILE_SIZE) {
        			throw new DataDeliveryException("파일 크기는 20MB보다 클 수 없습니다.", HttpStatus.BAD_REQUEST);
        		}
        		
        		// 서버 컴퓨터에 파일을 넣을 디렉토리가 있는지 검사
        		String saveDirectory = Define.UPLOAD_FILE_DERECTORY;
        		File directory = new File(saveDirectory);
        		if(!directory.exists()) {
        			directory.mkdirs();
        		}
        		
        		// 파일 이름 생성 (파일명 중복 예방)
        		String uploadFileName = UUID.randomUUID()+"_"+mFile.getOriginalFilename();
        		
        		// 파일 전체 경로 + 새로 생성한 파일명
        		String uploadPath = saveDirectory+uploadFileName;
        		System.out.println("------------------------------");
        		System.out.println(uploadPath);
        		System.out.println(uploadFileName);
        		System.out.println("------------------------------");
        		File destination = new File(uploadPath);
        		
        		// 반드시 수행
        		try {
        			mFile.transferTo(destination);
        		} catch (IllegalStateException | IOException e) {
        			e.printStackTrace();
        			throw new DataDeliveryException("파일 업로드 중에 오류가 발생했습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
        		}
        		
        		return new String[] {mFile.getOriginalFilename(), uploadFileName};
        	}

         

        728x90
        반응형

        'Springboot' 카테고리의 다른 글

        [Springboot] 36. 존재하지 않는 경로에 대한 요청 처리  (0) 2024.08.14
        [Springboot] 35. 파일 업로드(3단계-ResourceHandler 사용하기)  (1) 2024.08.14
        [Springboot] 33. 파일 업로드(1단계-멀티 파트란?)  (0) 2024.08.13
        [Springboot] 32. 사용자 비밀번호 암호화 처리  (0) 2024.08.13
        [Springboot] 31. DB 마이그레이션 (H2->MySQL)  (0) 2024.08.13
        다음글
        다음 글이 없습니다.
        이전글
        이전 글이 없습니다.
        댓글
      조회된 결과가 없습니다.
      스킨 업데이트 안내
      현재 이용하고 계신 스킨의 버전보다 더 높은 최신 버전이 감지 되었습니다. 최신버전 스킨 파일을 다운로드 받을 수 있는 페이지로 이동하시겠습니까?
      ("아니오" 를 선택할 시 30일 동안 최신 버전이 감지되어도 모달 창이 표시되지 않습니다.)
      목차
      표시할 목차가 없습니다.
        • 안녕하세요
        • 감사해요
        • 잘있어요

        티스토리툴바