Springboot

[Springboot] 33. 파일 업로드(1단계-멀티 파트란?)

Song hyun 2024. 8. 13. 14:51
728x90
반응형

[Springboot] 33. 파일 업로드(1단계-멀티 파트란?)

 

1. 멀티 파트란? (Multipart)

-멀티 파트란 HTTP 프로토콜을 사용하여, 웹 서버로 파일이나 이터를 업로드 할 떄 사용되는 데이터 전송 방식 중 하나입니다.

 

 

2. 스프링 프레임워크에서의 멀티파트 처리

 

3. 회원가입 시 파일 업로드 기능 구현

(1) application.yml

spring:
  mvc:
    view: 
      prefix: /WEB-INF/view/ #JSP파일이 위치한 디렉토리 접두사를 설정합니다.
      suffix: .jsp #뷰 이름에 자동으로 추가될 파일 확장자를 설정합니다.
  servlet:
    multipart:
      max-file-size: 20MB #파일 최대 크기 20MB
      max-request-size: 20MB #멀티파트 전체 요청 크기 제한 
  datasource:
    url: jdbc:mysql://localhost:3306/mybank?serverTimeZone=Asia/Seoul #데이터 베이스 연결을 위한 URL을 설정 합니다.
    driver-class-name: com.mysql.cj.jdbc.Driver #드라이버 클래스를 설정 합니다.
    username: root #사용자 ID를 지정
    password: asd123 #DB 비밀번호 여기서는 빈 문자열로 설정
  sql:
    init:
      schema-locations:
      - classpath:db/table.sql
      data-locations:
      - classpath:db/data.sql

 

 

(2) 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"%>

 

 

(3) UserService - createUser()

/**
	 * 회원 등록 서비스 기능
	 * 트랜잭션 처리  
	 * @param dto
	 */
	@Transactional // 트랜잭션 처리는 반드시 습관화 
	public void createUser(SignUpDTO dto) {
		int result = 0; 
		
		System.out.println(dto.getMFile().getOriginalFilename());
		
		
		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) SignUp.DTO

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();
	} 
	
	
}

 

728x90
반응형