Skip to content

Commit

Permalink
feat : file get
Browse files Browse the repository at this point in the history
  • Loading branch information
NameIsUser06 committed Dec 27, 2023
1 parent 1a3fcd7 commit 16960b5
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package org.bssm.attachit.domain.file.presentation;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.bssm.attachit.domain.file.service.GetFileService;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

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

private final GetFileService getFileService;

@GetMapping
public ResponseEntity<Resource> getFile(@RequestParam("attachmentId") Long id, HttpServletRequest httpServletRequest) throws IOException {
return getFileService.execute(id, httpServletRequest);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package org.bssm.attachit.domain.file.service;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.bssm.attachit.domain.attachment.domain.Attachment;
import org.bssm.attachit.domain.attachment.exception.FileNotFoundException;
import org.bssm.attachit.domain.attachment.repository.AttachmentRepository;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
@RequiredArgsConstructor
public class GetFileService {

private final AttachmentRepository attachmentRepository;

public ResponseEntity<Resource> execute(Long id, HttpServletRequest httpServletRequest) throws IOException {
Attachment attachment = attachmentRepository.findById(id).orElseThrow(
() -> FileNotFoundException.EXCEPTION
);
Path path = Paths.get(attachment.getPath());
Resource resource = new UrlResource(path.toUri());
String contentType = httpServletRequest.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(contentType)
.body(resource);
}
}
4 changes: 2 additions & 2 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ spring:
max-file-size: 20MB

jpa:
show-sql: true
show-sql: false
hibernate:
ddl-auto: create
ddl-auto: update
open-in-view: false


Expand Down

0 comments on commit 16960b5

Please sign in to comment.