KOSA Spring - 파일 업로드

채정윤·2025년 4월 23일

Spring

목록 보기
21/25

예제

🗺️ web.xml

경로 및 정보 설정

		<multipart-config>
			<location>D:\\upload\\temp</location>
			<max-file-size>20971520</max-file-size>
			<!-- 1MB * 20 -->
			<max-request-size>41943040</max-request-size>
			<!-- 40MB -->
			<file-size-threshold>20971520</file-size-threshold>
			<!-- 20MB -->
		</multipart-config>

◻️ servlet-content.xml

필요한 객체 생성

	<beans:bean id="multipartResolver"
		class = "org.springframework.web.multipart.support.StandardServletMultipartResolver"></beans:bean>

uploadForm.jsp

제출폼 만들기

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<form action="uploadFormAction" method="post" enctype="multipart/form-data">

<input type='file' name='uploadFile' multiple>

<button>Submit</button>

</form>

</body>
</html>

🧑‍💼 UploadController.java

package org.zerock.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import lombok.extern.log4j.Log4j;

@Controller
@Log4j
public class UploadController {
	
	@GetMapping("/uploadForm")
	public void uploadForm() {
		
	}
	
	@PostMapping("/uploadFormAction")
	public void uploadFormAction(MultipartFile uploadFile) {
		log.info("file Name: " + uploadFile.getOriginalFilename());
		log.info("file Size: " + uploadFile.getSize());
		
		File saveFile = new File(uploadFile.getOriginalFilename());
		
		try {
			uploadFile.transferTo(saveFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
//	INFO : org.zerock.controller.UploadController - file Name: image (55).png
//	INFO : org.zerock.controller.UploadController - file Size: 10792

}

**uploadFormAction(MultipartFile uploadFile)

  • POST 요청(/uploadFormAction**) 처리
  • 업로드된 파일을 MultipartFile로 받아옴
  • 파일을 서버에 저장
  • 파일 이름과 파일 크기를 로그로 출력

0개의 댓글