Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

기록

JAVA Spring 파일업로드 설정 및 업로드하기 본문

JAVA

JAVA Spring 파일업로드 설정 및 업로드하기

9400 2023. 1. 27. 12:03

설정 

1)pom.xml

    <!-- 파일 업로드시작 -->
    <!-- commons-fileupload 라이브러리는 tomcat7.0버전 이후로는
        서블릿3.0이상에서 지원함  -->
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>

        <!-- 썸네일 -->
        <!-- https://mvnrepository.com/artifact/org.imgscalr/imgscalr-lib -->
            <dependency>
                <groupId>org.imgscalr</groupId>
                <artifactId>imgscalr-lib</artifactId>
                <version>4.2</version>
            </dependency>

        <!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>
    <!-- 파일 업로드끝 -->

 

root-context.xml

	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 파일 업로드 용량(10MB) -->
		<property name="maxUploadSize" value="10485760"></property>
		<property name="defaultEncoding" value="UTF-8"></property>
	</bean>
	
	<!-- 파일업로드 디렉토리 설정 -->
	<bean id="uploadPath" class="java.lang.String">
		<constructor-arg value="c:\\upload" />
	</bean>

 

 

web.xml

		<!-- web.xml의 설정은 tomcat 자체 설정 -->
		<multipart-confi>
			<location>C:\\upload</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>
		</multipart-confi>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- multipart fileter추가 -->
	<filter>
		<display-name>springMultipartFilter</display-name>
		<filter-name>springMultipartFilter</filter-name>
		<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springMultipartFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

 

Servers - context.xml

<Context allowCasualMultipartParsing="true">

	<!-- 캐시문제 해결 -->
	<Resources cashingAllowed="true" cacheMaxSize="100000"></Resources>
	
    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
</Context>

 

 

 

	//요청URL : /lprod/uploadForm
	//요청방식 : get
	@GetMapping("/uploadForm")
	public String uploadForm() {
		//forwarding
		return "lprod/uploadForm";
	}

 

jsp

<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!-- 파일업로드
1)method는 꼭 post!
2)enctype="multipart/form-data"
3)<input type="file" name=".." name 속성이 반드시 있어야함! 
 -->
<script type="text/javascript" src="/resources/js/jquery-3.6.0.js"></script>
<script type="text/javascript">
$(function(){
	//이미지 미리보기
	let sel_file = [];
	$("#input_imgs").on("change",handleImgFileSelect);
	$("#input_imgs2").on("change",handleImgFileSelect);
	
	//파라미터 e:onchage 이벤트 객체
	function handleImgFileSelect(e){
		//이벤트가 발생된 타겟 안에 들어있는 이미지 파일들을 가져옴
		let files = e.target.files;
		//이미지가 여러개 있을 수 있으므로 이미지들을 분리해서 배열로 만듦
		let fileArr = Array.prototype.slice.call(files);
		//파일 오브젝트의 배열 반복. f : 배열 안에 들어있는 각각의 이미지 파일 객체
		
		fileArr.forEach(function(f){
			//이미지 파일이 아닌 경우 이미지 미리보기 실패 처리(image/jpeg)
			if(!f.type.match("image.*")){
				alert("이미지 확장자만 가능합니다.");
				//함수종료
				return;
			}	
			//이미지 객체(f)를 전역 배열타입 변수(sel_file)에 넣자
			sel_file.push(f);
			//이미지 객체를 읽을 자바스크립트의 reader 객체 생성                                                       
			let reader = new FileReader();
			//e : reader객체가 이미지를 읽는 이벤트
			reader.onload = function(e){
				//e.target : 이미지 객체
				//e.target.result : reader가 이미지를 다 읽은 결과
				let img_html = "<p><img src=\""+e.target.result+"\" /></p>";
				//객체.append : 누적, .html : 새로고침, innerHTML : J/S
				$('.imgs_wrap').append(img_html);
			}
 			reader.readAsDataURL(f); 
			
		}); //end for
	}
});


</script>

<!-- 
	요청 url : /lprod/uploadFormAction
	요청파라미터 : uploadFile이라는 이름의 파일 객체
	요청방식 : post
 -->
 <div class="imgs_wrap"></div> 
 <form action="/lprod/uploadFormAction" method="post"
		enctype="multipart/form-data">
	<input type="file" id="input_imgs" name="uploadFile" />
	<button type="submit">업로드</button>
</form>
<hr />

<!-- 
	요청 url : /lprod/uploadFormMultiAction
	요청파라미터 : uploadFile이라는 이름의 파일 객체
	요청방식 : post
 -->
 <form action="/lprod/uploadFormMultiAction" method="post"
		enctype="multipart/form-data">
	<input type="file" id="input_imgs2" name="uploadFile" multiple/>
	<button type="submit">다중업로드</button>
</form>

 

controller

	@PostMapping("/uploadFormAction")
	public String uploadFormAction(MultipartFile uploadFile) {
		//MultipartFile : 스프링에서 제공해주는 타입
		/*
		 * String, getOriginalFileName() : 업로드 되는 파일의 실제 파일명
		 * boolean, isEmpty() : 파일이 없다면 true
		 * long, getSize() : 업로드 되는 파일의 크기
		 * transferTo(File file) : 파일을 저장 
		 */
		//파일이 저장되는 경로
		String uploadFoler = "C:\\upload";
		
		log.info("----------");
		log.info("이미지명 : "+uploadFile.getOriginalFilename());
		log.info("파일 크기 : "+uploadFile.getSize());
		log.info("true?:"+uploadFile.isEmpty());
		
		//어디에?무엇을?
		//계획을 세움
		File savaFile = new File(uploadFoler,uploadFile.getOriginalFilename());
		
		//계획실행. 파일 복사됨(클라이언트의 파일을 서버의 공간을 복사)
		try {
			uploadFile.transferTo(savaFile);
		} catch (IllegalStateException e) {
			log.error(e.getMessage());
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		return "redirect:/lprod/uploadForm";
	}
	

	@PostMapping("/uploadFormMultiAction")
	public String uploadFormMultiAction(MultipartFile[] uploadFile) {
		//파일이 저장되는 경로
		String uploadFolder = "c:\\upload";
		
		for(MultipartFile multipartfile : uploadFile) {
			log.info("----------");
			log.info("이미지명 : "+multipartfile.getOriginalFilename());
			log.info("파일 크기 : "+multipartfile.getSize());
			log.info("컨텐츠(MIME)타입 : "+multipartfile.getContentType());
			log.info("true?:"+multipartfile.isEmpty());
			
			//어디에?무엇을?
			//계획을 세움
			File savaFile = new File(uploadFolder,multipartfile.getOriginalFilename());
			
			//계획실행. 파일 복사됨(클라이언트의 파일을 서버의 공간을 복사)
			try {
				multipartfile.transferTo(savaFile);
			} catch (IllegalStateException e) {
				log.error(e.getMessage());
			} catch (IOException e) {
				log.error(e.getMessage());
			}
		}
		
		return "redirect:/lprod/uploadForm";
	}
Comments