본문 바로가기
개발/Spring Boot

스프링 부트(springBoot) jsp 파일업로드 만들기

by chansungs 2023. 10. 10.
728x90
반응형

안녕하세요. 이번 포스팅에서는 파일 업로드를 만들어보겠습니다.

 

Spring MVC에서 파일 업로드 기능을 만들려면 MultipartResolver 설정하고, 컨트롤러에서 MultipartFile 객체를 사용하여 업로드된 파일을 처리해야 합니다.

 

1. 의존성 추가: Maven이나 Gradle 사용하는 경우, pom.xml 혹은 build.gradle 다음과 같이 의존성을 추가합니다.

 

Maven (pom.xml)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>

 

Gradle (build.gradle)

implementation 'org.springframework.boot:spring-boot-starter-web'

implementation 'commons-io:commons-io:2.8.0'

 

2. MultipartResolver 설정: Spring Boot 1.x 버전에서는 별도의 MultipartResolver 설정이 필요했지만, Spring Boot 2.x 이상에서는 자동으로 설정되므로 별도의 설정 없이 진행하시면 됩니다.

 

3. Controller 작성: 업로드된 파일을 처리하는 컨트롤러를 작성합니다.

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.multipart.MultipartFile;

 

@Controller

public class FileUploadController {

 

    @PostMapping("/upload")

    public String handleFileUpload(@RequestParam("file") MultipartFile file) {

        String uploadDirectory = "/path/to/upload/directory/";

 

        try {

            // Get the file and save it somewhere

            byte[] bytes = file.getBytes();

            Path path = Paths.get(uploadDirectory + file.getOriginalFilename());

            Files.write(path, bytes);

 

        } catch (IOException e) {

            e.printStackTrace();

        }

 

        return "redirect:/";

    }

}

 

4. JSP 페이지 작성: 파일 선택 업로드 버튼이 있는 JSP 페이지를 작성합니다.

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

   pageEncoding="UTF-8"%>

 

http://www.w3.org/TR/html4/loose.dtd">

<html>

 

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>File Upload Example in JSP and Servlet - Java web application tutorial</title>

<link rel='stylesheet' type='text/css' href='<%=request.getContextPath() %>/styles/main.css'/>

<style type='text/css'>

body {font-family:Arial, Sans-Serif;}

#container {width:600px; margin:auto;}

form {margin:20px 0;}

form input[type='submit'] {margin-top:30px;}

</style>

</head>

 

<body>

<div id='container'>

    <h1>Spring MVC File Upload Example</h1>

    <form method='POST' action='upload' enctype='multipart/form-data'>

        <input type="file" name="file"/>

        <input type="submit"/>

    </form>

</div>

</body>

 

</html>

 

5. 실행: 이제 애플리케이션을 실행하고 브라우저에서 http://localhost:{port}/your-jsp-page.jsp로 접속하여 파일 업로드를 테스트해 볼 수 있습니다.

이는 기본적인 예제이며, 실제 운영 환경에서는 보안 예외 처리, 파일 크기 제한, 파일 유형 제한 등의 추가적인 고려사항이 있습니다. 따라서 이러한 요소들을 고려하여 코드를 수정하거나 확장해야 합니다.

 

6. 파일 업로드 파일 크기 제한을 설정하려면 application.properties 또는 application.yml 파일에 해당 설정을 추가해야 합니다.

application.properties

spring.servlet.multipart.max-file-size=1MB

spring.servlet.multipart.max-request-size=10MB

 

application.yml

spring:

  servlet:

    multipart:

      max-file-size: 1MB

      max-request-size: 10MB

 

 

이 설정에서 max-file-size는 개별 파일의 최대 크기를, max-request-size는 전체 요청 본문의 최대 크기를 정의합니다. 위 예제에서는 개별 파일 크기가 1MB를 넘거나, 전체 요청 본문이 10MB를 넘으면 업로드가 거부됩니다.

참고로 이 값들은 바이트 단위로 지정할 수도 있습니다. 예를 들어, '1024B', '10KB', '200MB', '2GB' 등으로 표현할 수 있습니다.

또한 이러한 제한을 초과하면 MaxUploadSizeExceededException 발생합니다. 예외를 적절히 처리하여 사용자에게 친숙한 메시지나 페이지를 보여주도록 있습니다.

 

감사합니다.

 

 

728x90
반응형