반응형

Spring MVC를 사용한 파일 업로드와 다운로드 기능 구현 방법을 다룹니다. 전자정부프레임워크에서 파일 입출력은 자주 사용하는 기능으로, 오늘 학습을 통해 이를 효과적으로 구현할 수 있는 방법을 알아보겠습니다.


1. 파일 업로드 기능 구현

파일 업로드는 Multipart 요청을 처리해야 하며, Spring에서는 MultipartFile을 통해 이를 쉽게 구현할 수 있습니다.

1-1. 의존성 설정

전자정부프레임워크는 이미 필요한 설정을 포함하고 있지만, 파일 업로드를 위해 spring-web 모듈이 제대로 포함되어 있는지 확인하세요.

1-2. Controller 코드

파일 업로드 요청을 처리하는 기본 컨트롤러는 다음과 같습니다.

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
@RequestMapping("/file")
public class FileController {

    private final String UPLOAD_DIR = "C:/upload/";

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "파일이 업로드되지 않았습니다.";
        }

        try {
            String fileName = file.getOriginalFilename();
            File dest = new File(UPLOAD_DIR + fileName);
            file.transferTo(dest); // 파일 저장
            return "파일 업로드 성공: " + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "파일 업로드 실패: " + e.getMessage();
        }
    }
}

1-3. HTML 파일 업로드 폼 예제

아래는 파일 업로드를 테스트하기 위한 간단한 HTML 코드입니다.

<!DOCTYPE html>
<html>
<head>
    <title>파일 업로드</title>
</head>
<body>
    <form action="/file/upload" method="post" enctype="multipart/form-data">
        <label>파일 선택:</label>
        <input type="file" name="file">
        <button type="submit">업로드</button>
    </form>
</body>
</html>

2. 파일 다운로드 기능 구현

파일 다운로드는 서버에 저장된 파일을 HTTP 응답으로 전달하는 작업입니다.

2-1. Controller 코드

파일 다운로드를 처리하는 컨트롤러는 다음과 같습니다.

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/file")
public class FileController {

    private final String UPLOAD_DIR = "C:/upload/";

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam("filename") String filename) {
        try {
            Path filePath = Paths.get(UPLOAD_DIR + filename);
            Resource resource = new UrlResource(filePath.toUri());

            if (!resource.exists()) {
                return ResponseEntity.notFound().build();
            }

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                    .body(resource);

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
}

2-2. 파일 다운로드 요청 URL 예시

파일 다운로드는 브라우저 주소창 또는 HTML 링크로 요청할 수 있습니다.

<!DOCTYPE html>
<html>
<head>
    <title>파일 다운로드</title>
</head>
<body>
    <a href="/file/download?filename=sample.txt">sample.txt 다운로드</a>
</body>
</html>

3. 파일 입출력 시 주의사항

  1. 파일 저장 경로
    • 업로드된 파일은 서버의 적절한 디렉터리에 저장해야 합니다.
    • 사용자가 파일 경로를 조작하지 못하도록 설정합니다.
  2. 파일명 처리
    • 파일명이 중복될 경우 덮어쓰기가 발생할 수 있으므로, 고유한 파일명을 생성하는 로직을 추가하세요.
    String uniqueFileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
    
  3. 보안 고려
    • 업로드 가능한 파일 형식을 제한합니다. 예: .jpg, .png, .pdf 등.
    • 파일을 저장하기 전에 바이러스 검사를 수행하거나 무해한 폴더에 저장합니다.
  4. 파일 크기 제한
    • 서버 설정 또는 애플리케이션에서 파일 크기 제한을 적용합니다.
    • application.properties에서 파일 크기 제한 설정:
      spring.servlet.multipart.max-file-size=10MB
      spring.servlet.multipart.max-request-size=10MB
      

4. 확장 과제

  • 다중 파일 업로드
    여러 파일을 동시에 업로드하는 기능 추가.
  • 파일 목록 제공
    업로드된 파일 목록을 브라우저에 출력하고 다운로드할 수 있도록 구현.
  • AWS S3 연동
    클라우드 스토리지 서비스와의 연동으로 파일 관리 확장.

5. 마무리

파일 업로드와 다운로드는 대부분의 웹 애플리케이션에서 중요한 기능입니다. 오늘 학습한 내용을 기반으로 파일 관련 작업을 효과적으로 구현하고, 보안 및 성능을 최적화하는 방법까지 익혀보세요.
다음에서는 전자정부프레임워크 기반의 로그인 인증 처리를 학습합니다.

반응형

+ Recent posts