download

youngkyu MIn·2024년 5월 13일

@Controller
@RequestMapping("/genFile")
@Transactional(readOnly = true)
@RequiredArgsConstructor
@Tag(name = "GenFileController", description = "파일 다운로드 등 다양한 기능 제공")
public class GenFileController {
    private final GenFileService genFileService;

    @GetMapping("/download/{fileName}")
    @Operation(summary = "파일 다운로드")
    public ResponseEntity<Resource> download(
            @PathVariable String fileName, HttpServletRequest request
    ) throws FileNotFoundException {
        GenFile genFile = genFileService.findByFileName(fileName).orElseThrow(
                GlobalException.E404::new
        );
        String filePath = genFile.getFilePath();

        Resource resource = new InputStreamResource(new FileInputStream(filePath));

        String contentType = request.getServletContext().getMimeType(new File(filePath).getAbsolutePath());

        if (contentType == null) contentType = "application/octet-stream";

        String downloadFileName = Ut.url.encode(genFile.getOriginFileName()).replace("%20", " ");

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + downloadFileName + "\"")
                .contentType(MediaType.parseMediaType(contentType)).body(resource);
    }
}
profile
한 줄 소개

0개의 댓글