뭐든 즐기면서 ;)

Java Spring Boot File download 본문

BACK/JAVA

Java Spring Boot File download

Tada.*+ 2024. 10. 23. 15:16
728x90
package ai.maum.lom.api.retriever.file;

import ai.maum.lom.api.common.BaseException;
import ai.maum.lom.api.meta.ResponseCode;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriUtils;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {
    private final FileService fileService;

    @GetMapping("/download")
    public ResponseEntity<?> downloadFile(
            @RequestParam("file_id") Long fileId
    ) {
        FileEntity fileEntity = fileService.getFile(fileId);
        
        if(fileEntity == null)
            return ResponseEntity
                    .badRequest()
                    .body('프레임워크에 맞는 응답 형식 내려주기');

        Path filePath = Paths.get(fileEntity.getPath());

        try {
            Resource resource = new InputStreamResource(Files.newInputStream(filePath)); // 파일 resource 얻기

            // 파일 이름 UTF-8 인코딩
            String encodedFileName = UriUtils.encode(fileEntity.getOrgName(), StandardCharsets.UTF_8);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentDisposition(ContentDisposition
                    .attachment()
                    .filename(encodedFileName)  // 인코딩된 파일명을 설정
                    .build());

            return new ResponseEntity<>(resource, headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>('프레임워크에 맞는 응답 형식 내려주기', HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

 

getFile은 DB로부터 파일 정보를 가져오는 로직임.

fileEntity.getPath는 파일 경로 '.../.../파일명.ext' 확장자까지.

@Service
@RequiredArgsConstructor
public class FileService {
    private final FileRepository fileRepository;

    public FileEntity getFile(Long fileId) {
        Optional<FileEntity> fileEntity = fileRepository.findById(fileId);

        return fileEntity == null || fileEntity.isEmpty() ? null : fileEntity.get();
    }
}

 

Swagger로 확인하면, 'Response body' 영역에 아래와 같이 표시가 된다. url로 요청하게 되면 파일 다운로드됨.

728x90

'BACK > JAVA' 카테고리의 다른 글

JAVA Docker 실행  (0) 2023.12.12
FFmpeg window 설치  (0) 2023.10.20
request.getInputstream 여러 번 하는 방법  (0) 2023.07.20
Tomcat java version 확인  (0) 2023.05.25
HashMap getOrDefault 함수  (0) 2022.07.05
Comments