반응형

Spring boot Rest API 파일 업로드 및 다운로드 예제 (2)입니다.

이전 포스팅에 이어서 File Controller와 테스트를 할 수 있는 Swagger UI를 구현하겠습니다.


 

0. [Spring boot] REST API 기본 환경설정 및 CRUD 예제 참고 (1) ~ (6)

[SPRING BOOT] REST API 간단 예제 - (1) 프로젝트 생성

 

 

1. 이전 글 참고

- [SPRING BOOT] REST API File 예제 - (1) VO, Service

 

 

2. 환경

- Visual Studio Code : 1.61.2 version

- Spring boot : 2.5.7 version / gradle

- java 11

 

 

3. FileController.java

package com.test.demo.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

import com.test.demo.service.FileService;
import com.test.demo.vo.FileVO;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;

@Api(tags = {"01. File"}, description = "파일 관련 서비스")
@RestController
public class FileController {

  private FileService fileService;

  @Autowired
  public FileController(FileService fileService) {
    this.fileService = fileService;
  }
  
  @ApiOperation(value = "파일 업로드", notes = "파일을 업로드한다")
  @PostMapping(value = "/files")
  public ResponseEntity<String> uploadFile(MultipartFile[] files) 
  throws IllegalStateException, IOException {
    for (MultipartFile file : files) {
      fileService.store(file);
    }

    return new ResponseEntity<>("", HttpStatus.OK);
  }

  @ApiOperation(value = "파일 다운로드", notes = "파일을 다운로드한다")
  @GetMapping(value = "/files/{filename}/download")
  public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
    Resource file = fileService.loadAsResource(filename);

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

  @ApiOperation(value = "파일 목록 조회", notes = "파일 목록을 조회한다")
  @GetMapping("/files") 
  public ResponseEntity<List<FileVO>> getAllFiles() {
    List<FileVO> fileInfoList = fileService.loadAll().map(path -> {
      FileVO data = new FileVO();
      String filename = path.getFileName().toString();

      data.setFile_path(MvcUriComponentsBuilder.fromMethodName(
          FileController.class, "serveFile", filename
      ).build().toString());
      data.setFile_preview_path(MvcUriComponentsBuilder.fromMethodName(
          FileController.class, "getFilePreview", filename
      ).build().toString());
      data.setOriginal_name(filename);
      data.setFile_type(filename.substring(filename.lastIndexOf(".")));
      
      return data;

    }).collect(Collectors.toList());

    return ResponseEntity.status(HttpStatus.OK).body(fileInfoList);
  }

  @ApiOperation(value = "파일 미리보기")
  @GetMapping(
    value = "/files/{filename}/preview",
    produces = MediaType.IMAGE_JPEG_VALUE
  )
  public ResponseEntity<byte[]> getFilePreview(@PathVariable String filename) 
  throws IOException {
    InputStream in = new FileInputStream(fileService.load(filename).toString());

    return ResponseEntity.status(HttpStatus.OK).body(IOUtils.toByteArray(in));
  }

  @ApiOperation(value = "모든 파일 삭제")
  @DeleteMapping(value = "/files") 
  public ResponseEntity<String> deleteAll() {
    fileService.deleteAll();

    return new ResponseEntity<>("", HttpStatus.OK);
  }

  @ApiOperation(value = "파일 삭제")
  @DeleteMapping(value = "/files/{filename}")
  public ResponseEntity<String> deleteFile(@PathVariable String filename) {
    fileService.deleteFile(filename);
    
    return new ResponseEntity<>("", HttpStatus.OK);
  }
  
}

- File 컨트롤러입니다.

- 파일 목록 조회, 파일 업로드, 파일 다운로드, 파일 미리보기, 모든 파일 삭제, 파일 삭제 기능을 구현했습니다.

- 파일 업로드는 MultipartFile을 이용하여 한번에 여러개 올릴 수 있도록 구현했습니다.

 

 

4. Swagger UI 환경설정 및 구현 참고

[SPRING BOOT] REST API 간단 예제 - (5) Swagger UI 설정

[SPRING BOOT] REST API 간단 예제 - (6) Swagger UI 꾸미기

 

 

5. Swagger UI 화면

 

Swagger UI 화면

- 앞서 만든 File 서비스의 Swagger UI 화면입니다.

- "http://localhost:8080/swagger-ui.html" 링크로 접속하면 위와 같은 화면을 볼 수 있습니다.

 

- 컨트롤러에서 설정한 대로 서비스 목록이 생성되었습니다.

- Swagger UI의 환경설정 및 사용 방법에 대해서는 위 4번에 첨부된 링크를 이용해주시기 바랍니다.

 

 

 

이상으로 Spring boot Rest API 파일 업로드 예제 중 Controller와 Swagger UI를 구현해보았습니다.


 

반응형