본문 바로가기
개발 공부 Today I Learned

[국비 75일차 TIL] 전자정부 프레임워크 스프링 파일 업로드 fileUp

by 개발자신입 2024. 3. 12.
반응형

파일 업로드 fileUp

IndexController

	@GetMapping("/fileUp")
	public String fileUp() {
		return "fileUp";
	}

fileUp.html

<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>파일 업로드</title>
<th:block th:insert="~{menu.html :: head}" />
</head>
<body>
	<th:block th:insert="~{menu.html :: menu}" />

	<aside class="text-center">
		<div class="container px-5">
		<h1>파일 업로드</h1>
			<div class="col-md-4 mx-auto">
				<form action="/fileUp" method="post" enctype="multipart/form-data">
					<input type="file" name="fileUp">
					<button type="submit">업로드</button>
				</form>
			</div>
		</div>
	</aside>

	<!-- footer -->
	<th:block th:insert="~{menu.html :: footer}" />

	<!-- Add Bootstrap JS and Popper.js scripts (required for Bootstrap functionality) -->
	<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

	<!-- Feedback Modal-->
	<!-- Bootstrap core JS-->
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
	<!-- Core theme JS-->
	<script src="js/scripts.js"></script>
	<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *-->
	<!-- * *                               SB Forms JS                               * *-->
	<!-- * * Activate your form at https://startbootstrap.com/solution/contact-forms * *-->
	<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *-->
	<script src="https://cdn.startbootstrap.com/sb-forms-latest.js"></script>
</body>
</html>

IndexController.java

	// 2024-03-12 파일 업로드
	@GetMapping("/fileUp")
	public String fileUp() {
		return "fileUp";
	}
	
	@PostMapping("/fileUp")
	public String fileUp(@RequestParam("fileUp") MultipartFile file) {
		System.out.println(file.getName());
		System.out.println(file.getSize());
		System.out.println(file.getOriginalFilename());
		
		return "redirect:/fileUp";
	}

application.properties

# fileUp
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=50MB
spring.servlet.multipart.enabled=true

IndexController.java

	@PostMapping("/fileUp")
	public String fileUp(@RequestParam("fileUp") MultipartFile file) {
		System.out.println(file.getName());
		System.out.println(file.getSize());
		System.out.println(file.getOriginalFilename());
		
		// String url = util.req().getServletContext().getRealPath("/upload");
		
		// String 타입을 file 타입으로 만들어줌. -> 경로 만들어주도록.
		File url = new File(util.req().getServletContext().getRealPath("/upload"));
		url.mkdirs();
		
		// mkdirs의 결과가 url로 들어감.
		File upFileName = new File(url, file.getOriginalFilename());
		
		try {
			file.transferTo(upFileName);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		} 
		
		System.out.println("실제 경로 : "+url);
		
		return "redirect:/fileUp";
	}

파일 업로드 페이지에서 파일을 업로드하면 url에 업로드 한 파일이 저장됨. 


파일명 중복되지 않도록 하는 방법

  •  UUID
  •  년월일시분초
  •  나노초
 		// UUID 방법
		UUID uuid = UUID.randomUUID();
		System.out.println("원본 파일명 " + file.getOriginalFilename());
		System.out.println("UUID 파일명 " + uuid.toString() + file.getOriginalFilename());
		
		// date 방법
		LocalDateTime ldt = LocalDateTime.now();
		String ldtFormat = ldt.format(DateTimeFormatter.ofPattern("YYYYMMddHHmmSS"));
		System.out.println("날짜 파일명 " + ldtFormat + file.getOriginalFilename());

 

<출력 결과>

원본 파일명 : delete2.png
UUID 파일명 : b1d71230-d953-47ef-803c-1bc8090a9c2bdelete2.png
날짜 파일명 : 20240312101003delete2.png


ldtFormat을 원본 파일명 앞에 추가함.

File upFileName = new File(url, ldtFormat + file.getOriginalFilename());

fileUp.html

img 폴더 생성 후 이미지 업로드

	<aside class="text-center">
		<div class="container px-5">
		<h1>파일 업로드</h1>
			<div class="col-md-4 mx-auto">
				<form action="/fileUp" method="post" enctype="multipart/form-data">
					<input type="file" name="fileUp">
					<button type="submit">업로드</button>
				</form>
			</div><br>
			<button onclick="location.href='/downfile@img1.png'">이미지 다운로드</button>
			<br><br>
			<img alt="img" src="/img/img1.png">
		</div>
	</aside>

IndexController.java

	// downfile@파일명
	@ResponseBody
	@GetMapping("/downfile@{file}") // path variable
	public void down(@PathVariable("file") String file, 
					HttpServletRequest request, 
					HttpServletResponse response) {
		System.out.println("경로에 들어온 파일명 : "+file);
		
		File url = new File(util.req().getServletContext().getRealPath("/upload"));
		File serverFile = new File(url, file); // 다운받을 경로
		
		try {
			byte[] fileByte = FileCopyUtils.copyToByteArray(serverFile);
			response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition", "attachment fileName=\""
								+URLEncoder.encode(url+file, "UTF-8")+"\";");
			response.setHeader("Content-Transfer-Encoding", "binary");
			response.getOutputStream().write(fileByte);
			response.getOutputStream().flush(); // 남아있는거 다 전송
			response.getOutputStream().close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 Gradle Tasks 

* 경로 : 프로젝트명 -  web - bootjar - Run Gradle Tasks

 

여기에서 생긴 jar 파일은 작업중인 프로젝트 파일임.

이 jar파일은 cmd에서 구동 가능

 

1. 경로로 접속

Microsoft Windows [Version 10.0.19045.4046]
(c) Microsoft Corporation. All rights reserved.

C:\Users\user>cd C:\eGovFrameDev-4.1.0-64bit\workspace\web\build\libs

2.  dir로 파일 검색

C:\eGovFrameDev-4.1.0-64bit\workspace\web\build\libs>dir
 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: 5EA5-0099

 C:\eGovFrameDev-4.1.0-64bit\workspace\web\build\libs 디렉터리

2024-03-12  오전 11:43    <DIR>          .
2024-03-12  오전 11:43    <DIR>          ..
2024-03-12  오전 11:43        34,372,701 web-0.0.1-SNAPSHOT.jar
               1개 파일          34,372,701 바이트
               2개 디렉터리  160,155,918,336 바이트 남음

3. jar파일 실행


C:\eGovFrameDev-4.1.0-64bit\workspace\web\build\libs>java -jar web-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.2.3)

2024-03-12T11:47:14.548+09:00  INFO 9368 --- [           main] com.example.web.WebApplication           : Starting WebApplication v0.0.1-SNAPSHOT using Java 17.0.10 with PID 9368 (C:\eGovFrameDev-4.1.0-64bit\workspace\web\build\libs\web-0.0.1-SNAPSHOT.jar started by user in C:\eGovFrameDev-4.1.0-64bit\workspace\web\build\libs)
2024-03-12T11:47:14.553+09:00  INFO 9368 --- [           main] com.example.web.WebApplication           : No active profile set, falling back to 1 default profile: "default"
2024-03-12T11:47:16.655+09:00  INFO 9368 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 80 (http)
2024-03-12T11:47:16.674+09:00  INFO 9368 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2024-03-12T11:47:16.674+09:00  INFO 9368 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.19]
2024-03-12T11:47:16.736+09:00  INFO 9368 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2024-03-12T11:47:16.738+09:00  INFO 9368 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2064 ms
2024-03-12T11:47:17.399+09:00  INFO 9368 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page template: index
2024-03-12T11:47:18.258+09:00  INFO 9368 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 80 (http) with context path ''
2024-03-12T11:47:18.285+09:00  INFO 9368 --- [           main] com.example.web.WebApplication           : Started WebApplication in 4.341 seconds (process running for 4.891)
2024-03-12T11:47:28.896+09:00  INFO 9368 --- [p-nio-80-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-03-12T11:47:28.896+09:00  INFO 9368 --- [p-nio-80-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2024-03-12T11:47:28.899+09:00  INFO 9368 --- [p-nio-80-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms
시작할 때 : fileUp
시작할 때 : public java.lang.String com.example.web.controller.IndexController.fileUp()
[]
fileUp 메소드가 종료됨
시작할 때 : index
시작할 때 : public java.lang.String com.example.web.controller.IndexController.index(org.springframework.ui.Model)
[{}]
파라미터 타입 : BindingAwareModelMap
파라미터 값 : {}
2024-03-12T11:47:30.717+09:00  INFO 9368 --- [p-nio-80-exec-5] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2024-03-12T11:47:30.906+09:00  INFO 9368 --- [p-nio-80-exec-5] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection org.mariadb.jdbc.Connection@3b26d409
2024-03-12T11:47:30.909+09:00  INFO 9368 --- [p-nio-80-exec-5] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
index 메소드가 종료됨

 

반응형

댓글