[java] Spring MVC에서 파일 업로드 및 다운로드 처리 방법

Spring MVC는 파일 업로드 및 다운로드를 처리하기 위한 강력한 기능을 제공합니다. 이 기능을 이용하여 사용자가 파일을 업로드하고 서버에서는 업로드된 파일을 다운로드할 수 있습니다. 이번 포스트에서는 Spring MVC를 사용하여 파일 업로드 및 다운로드를 처리하는 방법을 알아보겠습니다.

파일 업로드 처리

  1. pom.xml에 commons-fileuploadcommons-io 라이브러리를 추가합니다.
     <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.8.0</version>
     </dependency>
    
  2. Spring MVC 설정 파일에 MultipartResolver를 설정합니다.
     @Configuration
     public class WebMvcConfig implements WebMvcConfigurer {
    
         @Bean
         public MultipartResolver multipartResolver() {
             CommonsMultipartResolver resolver = new CommonsMultipartResolver();
             resolver.setMaxUploadSize(5242880); // 5MB
             return resolver;
         }
     }
    
  3. 파일을 업로드할 컨트롤러를 작성합니다.
     @Controller
     public class FileUploadController {
    
         @PostMapping("/upload")
         public String handleFileUpload(@RequestParam("file") MultipartFile file) {
             if (!file.isEmpty()) {
                 try {
                     byte[] bytes = file.getBytes();
                     // 파일을 저장 또는 처리하는 로직을 작성합니다.
                     // 예: 파일을 서버에 저장하는 코드
                     Path path = Paths.get("/path/to/save/file");
                     Files.write(path, bytes);
                     return "redirect:/success";
                 } catch (IOException e) {
                     e.printStackTrace();
                     return "redirect:/error";
                 }
             } else {
                 return "redirect:/error";
             }
         }
     }
    

파일 다운로드 처리

  1. 다운로드할 파일의 경로를 가지고 있는 컨트롤러를 작성합니다.
     @Controller
     public class FileDownloadController {
    
         @GetMapping("/download")
         public ResponseEntity<Resource> downloadFile() {
             // 다운로드할 파일 경로를 지정합니다.
             Path path = Paths.get("/path/to/file");
    
             ByteArrayResource resource;
             try {
                 resource = new ByteArrayResource(Files.readAllBytes(path));
             } catch (IOException e) {
                 e.printStackTrace();
                 return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
             }
    
             return ResponseEntity.ok()
                     .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + path.getFileName() + "\"")
                     .body(resource);
         }
     }
    
  2. 다운로드 링크를 제공하는 View를 작성합니다. ```html <!DOCTYPE html>
File Download Download File

```

이제 파일 업로드와 다운로드를 처리하는 Spring MVC 애플리케이션을 실행하고 테스트해 볼 수 있습니다.

이 문서는 Spring MVC에서 파일 업로드 및 다운로드를 처리하는 방법에 대한 간단한 예제를 제공했습니다. Spring MVC의 다른 기능 및 세부 설정에 대해서는 공식 문서나 다른 참고 자료를 참고하시기 바랍니다.