Spring - 파일 업로드하고 다운 받기





늘은 Spring 기반에서 파일을 업로드하고, 파일 내역을 확인해서 다운받는 예제입니다. pom.xml에 파일 업다운을 위한 별도의 코드가 들어있고, UploadController에 관련 내용이 들어 있습니다.

파일 구조는 아래와 같이 되어 있습니다. 그리고 아래의 Github 주소에서 관련 파일 확인 가능합니다.






pack.upload 패키지

** DownloadController.java **
package pack.upload;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DownloadController {
    @RequestMapping("download")
    @ResponseBody
    public byte[] downProcess(HttpServletResponse response,
        @RequestParam String filename) throws IOException{
        File file = new File("c:/work/upload/" + filename);
        byte[] bytes = FileCopyUtils.copyToByteArray(file);
        
        String fn = new String(file.getName().getBytes(), "iso_8859_1");
        
        response.setHeader("Content-Disposition",
                "attachment;filename=\"" + fn + "\"");
        response.setContentLength(bytes.length);
        return bytes;
    }
}

/* 오류 내역
package pack.upload;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

public class DownloadController {
    @RequestMapping("download")
    @ResponseBody
    public byte[] downProcess(HttpServletResponse response,
            @RequestParam String filename) throws IOException{
        File file = new File("c:/work/upload/" + filename);
        byte[] bytes = FileCopyUtils.copyToByteArray(file);
        
        String fn = new String(file.getName().getBytes(), "iso_8859_1");
        
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fn + "\"");
        response.setContentLength(bytes.length);
        return bytes;
    }
}

*/

** FileValidator.java **
package pack.upload;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

@Component
public class FileValidator implements Validator {

    //파일 유무 확인용
    public boolean supports(Class<?> arg0) {
    
        return false;
    }
    
    public void validate(Object upFile, Errors errors) {
        UploadFile file = (UploadFile)upFile;
        
        if(file.getFile().getSize() == 0) {
            errors.rejectValue("file", ""," 업로드할 파일을 선택하시오");
        }
    }
}


** UploadController.java **
package pack.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UploadController {
    
    @Autowired
    private FileValidator fileValidator;
    
    @RequestMapping(value="upload", method=RequestMethod.GET)
    public String getUploadForm() {
        return "uploadform";
    }
    
    @RequestMapping(value="upload", method=RequestMethod.POST)
    public ModelAndView submitUpload(
            @ModelAttribute("uploadFile") UploadFile uploadFile,
            BindingResult result    ) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        
        // 에러 검사 : 업로드 파일 유무
        MultipartFile file = uploadFile.getFile();
        fileValidator.validate(uploadFile, result);
        
        String fileName = file.getOriginalFilename();
        if(result.hasErrors()) {
            //업로드할 파일을 선택하지 않은 경우 form에 에러 메세지를 출력함
            return new ModelAndView("uploadform");
        }
        
        try {
            inputStream = file.getInputStream();
            
            File newFile = new File("c:/work/upload/" + fileName);
            if(newFile.exists()) {
                newFile.createNewFile();
            }
            outputStream = new FileOutputStream(newFile);
            int read = 0;
            byte[] bytes = new byte[1024];
            
            while((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,read);
            }
            
        } catch (Exception e) {
            System.out.println("err : " + e);
        }finally {
            try {
                inputStream.close();
                outputStream.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
        
        
        return new ModelAndView("uploadfile", "filename", fileName);
    }
}



** UploadFile.java **
package pack.upload;

import java.util.List;

import org.springframework.web.multipart.MultipartFile;

public class UploadFile {            //File 처리용 dto
    private MultipartFile file;
    //private List<MultipartFile> file;

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }

    

}


src 폴더

** uploadfile.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>
<h3>upload 된 파일</h3>
파일명 : ${filename}
<br>
<form action="download" method="post">
    <input type="hidden" name="filename" value="${filename}">
    <input type="submit" value="다운로드">
</form>
</body>
</html>



** 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>
** 파일 업로드/다운로드 ** <br>
<%@ taglib prefix="form"  uri="http://www.springframework.org/tags/form" %>
<form:form enctype="multipart/form-data" modelAttribute="uploadFile">
업로드할 파일 선택 : <br>
<input type="file" name="file">
<form:errors path="file" cssStyle="color:red" />
<br><Br>
<input type="submit" value="전송">
</form:form>
</body>
</html>

** mvc-config.xml **
<?xml version="1.0" encoding="UTF-8"?>



    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
    

         <context:component-scan  base-package="pack.upload"/>


    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
            <property name="prefix" value="/WEB-INF/view/"/>
            <property name="suffix" value=".jsp"/>
    </bean>

</beans>


** web.xml **
<?xml version="1.0" encoding="ISO-8859-1"?>
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    id="WebApp_ID" version="2.5">

    <display-name>sweb27_fileupdown</display-name>

    <!-- - Location of the XML file that defines the root application context.
        - Applied by ContextLoaderListener. -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/application-config.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <!-- - Servlet that dispatches request to registered handlers (Controller
        implementations). -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>


** index.jsp **
<!DOCTYPE html>

<%@ 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="spring" uri="http://www.springframework.org/tags"%>

<html>
    <head>
        <meta charset="utf-8">
        <title>Welcome</title>
    </head>
    <body>
        <a href="upload">upload test</a>
    </body>
</html>



그 외

** pom.xml **
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.springframework.samples.service.service</groupId>
    <artifactId>sweb27_fileupdown</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>

        <!-- Generic properties -->
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <!-- Web -->
        <jsp.version>2.2</jsp.version>
        <jstl.version>1.2</jstl.version>
        <servlet.version>2.5</servlet.version>



        <!-- Spring -->
        <spring-framework.version>4.3.3.RELEASE</spring-framework.version>


        <!-- Logging -->
        <logback.version>1.0.13</logback.version>
        <slf4j.version>1.7.5</slf4j.version>

    </properties>

    <dependencies>

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

        <!-- Other Web dependencies -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- Spring and Transactions -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <!-- Logging with SLF4J & LogBack -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!--DB -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>2.2.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <!--mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- json -->
        <dependency>

            <groupId>com.fasterxml.jackson.core</groupId>

            <artifactId>jackson-databind</artifactId>

            <version>2.9.5</version>

        </dependency>
        
                <!-- AOP -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.6</version>
        </dependency>
        
        <!-- file up and down -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>
    
    <!-- utf-8 -->
        
    </dependencies>
</project>






결과 이미지



본 포스팅은 KIC 캠퍼스에서 박영권 강사의 지도하에 공부하며 작성한 리포트입니다.
혹시 잘못된 내용이 있거나 문제 소지시 댓글 남겨주시면 조치하겠습니다.









댓글(0)

Designed by CMSFactory.NET