ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • (다중)파일업로드 구현 순서
    spring framework 2021. 6. 17. 17:00

    0.jsp view부분 구현

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <html>
    <head>
    	<title>Home</title>
    </head>
    <body>
    	<form action="fileup" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
    		<input multiple="multiple" type="file" name="file"/>
    		<input type="submit" value="전송"/>
    	</form>
    </body>
    </html>
    

     

    1.maven 라이브러리 등록

    <!-- 파일업로드 -->
    		<dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.2</version>
            </dependency>
            
            <dependency>
            	<groupId>commons-io</groupId>
            	<artifactId>commons-io</artifactId>
            	<version>2.5</version>
            </dependency>

     

    2.servlet.xml 파일업로드 객체 생성

    <!-- file Upload -->
        <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- max upload size in bytes -->
            <beans:property name="maxUploadSize" value="5242880" /> <!-- 5MB -->
            <!-- max size of file in memory (in bytes) -->
            <beans:property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
        </beans:bean>
    <!-- Root Context: defines shared resources visible to all other web components -->
    	<beans:bean id="multipartResolver"
    		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    		<!-- 파일업로드 용량 (10MB) -->
    		<beans:property name="maxUploadSize" value="10485760" />
    		<beans:property name="defaultEncoding" value="UTF-8" />
    	</beans:bean>

     

     

    3.upload할 경로 string객체 생성(root-context.xml)

    <!-- Root Context: defines shared resources visible to all other web components -->
    	<bean id="uploadPath" class="java.lang.String">
    		<constructor-arg value="C:/Users/오지석/eclipse-workspace/pdftest/src/main/webapp/resources/image" />
    	</bean>	

     

    4.업로드 로직을 구현할 class에서 path 경로를 가져옴

    @Resource(name = "uploadPath")
    	String uploadPath;

        - 이때 resource 어노테이션이 활성화 되어져있지않으면 maven등록

    <!-- resource 어노테이션 사용 -->
    		<dependency>
    			<groupId>javax.annotation</groupId>
    			<artifactId>javax.annotation-api</artifactId>
    			<version>1.3.2</version>
    		</dependency>

     

    5.업로드 로직 구현

    @PostMapping("/fileup")
    	public String fileup(@RequestParam("file") MultipartFile[] file) {
    		
    		for(MultipartFile f : file)
    		{
    			String filename = f.getOriginalFilename();
    			
    			try {
    				f.transferTo(new File(uploadPath + "/" + filename));
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    		return "home";
    	}
Designed by Tistory.