헤르메스 LIFE

[Spring] 개발환경 구축 - File Upload 본문

Spring Framework

[Spring] 개발환경 구축 - File Upload

헤르메스의날개 2022. 12. 26. 00:04
728x90

SimpleSpring4.zip
0.05MB

Spring 개발환경을 갑자기 구축하려고 하다보니, 막막합니다.

하나 하나 구축해 보겠습니다


개발환경

Spring 4.3.30.RELEASE

MAVEN 3.8.4

Logback 1.2.9

commons-fileupload 1.4

commons-io 2.6


pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>SimpleSpring4</groupId>
    <artifactId>SimpleSpring4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>SimpleSpring4</name>
    <description>Simple Spring4</description>

    <properties>
        <springframework.version>4.3.30.RELEASE</springframework.version>

        <org.slf4j-version>1.7.30</org.slf4j-version><!-- 1.7.26 -->
        <ch.qos.logback-version>1.2.9</ch.qos.logback-version>
    </properties>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>

        <!-- slf4j -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>

        <!-- Bridge -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.25</version>
        </dependency>

        <!-- logback -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${ch.qos.logback-version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId><!-- logback을 slf4j-api에서 사용함을 의미 -->
                </exclusion>
            </exclusions>
            <scope>runtime</scope><!-- runtime 시 사용함 -->
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3</version>
        </dependency>
        <!-- For user input validation -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>

        <!-- commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.3</version>
            </plugin>
        </plugins>
    </build>
</project>

DispatcherServlet.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <mvc:annotation-driven />

    <!-- 빈 설정을 어노테이션 기반으로 하겠다는 설정태그 -->
    <context:component-scan base-package="simple">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- CSS, JS, 이미지 등의 자원은 거의 변하지 않기 때문에, 웹 브라우저에 캐시를 하면
         네트워크 사용량, 서버 사용량, 웹 브라우저의 반응 속도 등을 개선할 수 있다. -->
    <mvc:resources mapping="/static/**" location="/static/" />
    <mvc:resources location="/resources/**" mapping="/resources/"></mvc:resources>
    
    <!--
     Mulitipart Resolver
     maxUploadSize는 최대 업로드 가능한 파일의 바이트 크기
     maxInMemorySize는 디스크에 임시 파일을 생성하기 전 메모리에 보관할 수 있는 최대 바이트 크기
     -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8" />
        <property name="maxUploadSize" value="104857600" /> <!-- 10M -->
        <property name="maxInMemorySize" value="1048576" /> <!-- 1M -->
    </bean>

    <bean id="uploadPath" class="java.lang.String">
        <constructor-arg value="C:/project/upload/"></constructor-arg>
    </bean>
    
    
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <!-- Encoding 설정 -->
        <property name="defaultEncoding" value="UTF-8"/> 
        <!-- Reload Cache 설정 -->
        <property name="cacheSeconds" value="5"/>
        <!-- basenames 설정: 아래처럼 하면 WEB-INF 밑의 message 폴더 아래의 labels로 시작하는 모든 Property-->
        <property name="basenames">
            <list>
                <value>/WEB-INF/messages/message</value>
                <value>classpath:/messages/message</value>
            </list>
        </property>       
    </bean>
     
    <!-- MessageSource를 사용하기 위한 Accessor 설정 -->
    <bean id="messageSourceAccessor" class="org.springframework.context.support.MessageSourceAccessor">
        <constructor-arg ref="messageSource"/>
    </bean>

    <!-- Default Location 설정 -->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <property name="defaultLocale" value="ko"></property>
    </bean>
    
    <!--
     mvc:default-servlet-handler
     요청 경로와 일치하는 컨트롤러를 찾는다.
     컨트롤러가 존재하지 않으면, 디폴트 서블릿 핸들러에 전달한다.
     DispatcherSerlvet이 처리하지 못한 요청을 DefaultSerlvet에게 넘겨주는 역할을 하는 핸들러
     *.css와 같은 컨트롤러에 매핑되어 있지 않은 URL 요청은 최종적으로 Default Servlet에 전달되어 처리하는 역할
     
     
     web.xml 파일의 dispatcher 가 / 의 경우 설정한다.
     <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    -->
    <mvc:default-servlet-handler />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

singleFileUploader.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring 4 MVC File Upload Example</title>
<link href="<c:url value='/static/css/bootstrap.css' />" rel="stylesheet" type="text/css"></link>
<link href="<c:url value='/static/css/app.css' />" rel="stylesheet" type="text/css"></link>
</head>
<body>

    <div class="form-container">
        <h1>Spring 4 MVC File Upload Example</h1>
        <form method="post" action="/singleUpload" enctype="multipart/form-data" class="form-horizontal">

            <div class="row">
                <div class="form-group col-md-12">
                    <label class="col-md-3 control-lable" for="file">Upload a file</label>
                    <div class="col-md-7">
                        <input type="file" name="files" class="form-control input-sm" />
                        <div class="has-error">
                            <form:errors path="file" class="help-inline" />
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="form-actions floatRight">
                    <input type="submit" value="Upload" class="btn btn-primary btn-sm">
                </div>
            </div>
        </form>
        <a href="<c:url value='/welcome' />">Home</a>
    </div>
</body>
</html>

multiFileUploader.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring 4 MVC File Multi Upload Example</title>
<link href="<c:url value='/static/css/bootstrap.css' />" rel="stylesheet" type="text/css"></link>
<link href="<c:url value='/static/css/app.css' />" rel="stylesheet" type="text/css"></link>
</head>
<body>

    <div class="form-container">
        <h1>Spring 4 MVC Multi File Upload Example</h1>
        <form method="post" action="/singleUpload" enctype="multipart/form-data" class="form-horizontal">

            <input multiple="multiple" type="file" name="files" class="form-control input-sm"/>
            <div class="has-error">
                <form:errors path="files[${vs.index}].file" class="help-inline" />
            </div>
            <br />
            <div class="row">
                <div class="form-actions floatRight">
                    <input type="submit" value="Upload" class="btn btn-primary btn-sm">
                </div>
            </div>
        </form>

        <br /> <a href="<c:url value='/welcome' />">Home</a>
    </div>
</body>
</html>

FileUploadController.java

package simple.spring.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    // DispatcherServlet.xml 파일의 uploadPath bean의 constructor-arg를 가져옵니다.
    @Resource(name = "uploadPath")
    private String UPLOAD_LOCATION;

    @RequestMapping(value = "/singleUpload", method = RequestMethod.GET)
    public String getSingleUploadPage( ModelMap model ) {
        return "upload/singleFileUploader";
    }

    @RequestMapping(value = "/multiUpload", method = RequestMethod.GET)
    public String getMultiUploadPage( ModelMap model ) {
        return "upload/multiFileUploader";
    }

    @RequestMapping(value = "/singleUpload", method = RequestMethod.POST)
    public String singleFileUpload( @RequestParam("files") MultipartFile[] files, ModelMap model ) throws IOException {

        logger.debug("[FileUploadController.singleFileUpload] 파일개수 : {}", files.length);

        List<String> fileList = new ArrayList<>();

        if ( files.length > 0 ) {
            for ( int i = 0; i < files.length; i++ ) {
                String fileName = files[i].getOriginalFilename();
                String fileExt  = fileName.substring(fileName.lastIndexOf("."));

                logger.debug("[FileUploadController.singleFileUpload] UPLOAD_LOCATION : {}", UPLOAD_LOCATION);
                logger.debug("[FileUploadController.singleFileUpload] 파일 이름 : {}", fileName);
                logger.debug("[FileUploadController.singleFileUpload] 파일 확장자 : {}", fileExt);
                logger.debug("[FileUploadController.singleFileUpload] 파일 크기 : {}", files[i].getSize());

                String uuidFile = UUID.randomUUID().toString().replaceAll("-", "") + fileExt;

                logger.debug("[FileUploadController.singleFileUpload] UUID 파일명 : {}", uuidFile);

                String uploadFile = UPLOAD_LOCATION + uuidFile;

                logger.debug("[FileUploadController.singleFileUpload] 업로드 파일 : {}", uploadFile);

                try (
                        FileOutputStream fos = new FileOutputStream(uploadFile);
                        InputStream is = files[i].getInputStream(); ) {

                    File Folder = new File(uploadFile);
                    if ( !Folder.exists() ) {
                        try {
                            Folder.mkdirs();
                            System.out.println("폴더가 생성되었습니다.");
                        } catch (Exception e) {
                            e.getStackTrace();
                        }
                    }

                    int    readCount = 0;
                    byte[] buffer    = new byte[1024];
                    while ((readCount = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, readCount);
                    }
                } catch (Exception ex) {
                    throw new RuntimeException("file Save Error");
                }

                fileList.add(fileName);

            }

            model.addAttribute("fileNames", fileList);

            logger.debug("[FileUploadController.singleFileUpload] model :: {}", model);

        }

        return "upload/success";
    }

}

https://hermeslog.tistory.com/649

 

[Spring] 개발환경 구축 - MessagesSource

Spring 개발환경을 갑자기 구축하려고 하다보니, 막막합니다. 하나 하나 구축해 보겠습니다 개발환경 Spring 4.3.30.RELEASE MAVEN 3.8.4 Logback 1.2.9 DispatcherServlet.xml /WEB-INF/messages/message classpath:/messages/message

hermeslog.tistory.com

 

728x90