Skip to content

Commit

Permalink
Hotfix: 보고서 이미지 조회가 안되는 버그 수정
Browse files Browse the repository at this point in the history
* 보고서 이미지에 대한 모든 응답에 리소스 핸들러 경로를 포함

* 이미지를 DB에 저장할 때 파일명만 기록하도록 수정

* 서버 내 저장된 이미지를 찾을 수 없는 버그 수정
  • Loading branch information
zionhann committed Oct 23, 2023
1 parent 8393213 commit dd8965b
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 14 deletions.
6 changes: 3 additions & 3 deletions src/main/java/edu/handong/csee/histudy/config/WebConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ public class WebConfig implements WebMvcConfigurer {
@Value("${custom.path-patterns.include}")
private String[] includePathPatterns;

@Value("${custom.resource.path}")
private String imageBasePath;
@Value("${custom.resource.path-pattern}")
private String imageBasePathPattern;

@Value("${custom.resource.location}")
private String imageBaseLocation;
Expand All @@ -48,7 +48,7 @@ public void addCorsMappings(CorsRegistry registry) {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(imageBasePath)
registry.addResourceHandler(imageBasePathPattern)
.addResourceLocations("file://" + imageBaseLocation);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

Expand Down Expand Up @@ -55,9 +56,14 @@ public ResponseEntity<Integer> deleteTeam(
public ResponseEntity<TeamReportDto> getTeamReports(
@Parameter(description = "그룹 아이디", required = true)
@PathVariable(name = "id") long id,
@RequestAttribute Claims claims) {
@RequestAttribute Claims claims,
@Value("${custom.resource.path}") String imageBasePath) {
if (Role.isAuthorized(claims, Role.ADMIN)) {
return ResponseEntity.ok(teamService.getTeamReports(id, claims.getSubject()));
TeamReportDto res = teamService.getTeamReports(id, claims.getSubject());
res.getReports()
.forEach(report ->
report.addPathToFilename(imageBasePath));
return ResponseEntity.ok(res);
}
throw new ForbiddenException();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.map.SingletonMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
Expand All @@ -45,13 +46,20 @@ public class TeamController {
private final ImageService imageService;
private final UserRepository userRepository;

@Value("${custom.resource.path}")
String imageBasePath;

@Operation(summary = "그룹 스터디 보고서 생성")
@PostMapping("/reports")
public ReportDto.ReportInfo createReport(
@RequestBody ReportForm form,
@RequestAttribute Claims claims) {
if (Role.isAuthorized(claims, Role.MEMBER)) {
return reportService.createReport(form, claims.getSubject());
ReportDto.ReportInfo res = reportService.createReport(form, claims.getSubject());
res.getImages().forEach(image ->
image.addPathToFilename(imageBasePath));

return res;
}
throw new ForbiddenException();
}
Expand All @@ -62,6 +70,9 @@ public ReportDto getMyGroupReports(
@RequestAttribute Claims claims) {
if (Role.isAuthorized(claims, Role.MEMBER)) {
List<ReportDto.ReportInfo> reports = reportService.getReports(claims.getSubject());
reports.forEach(report ->
report.getImages().forEach(
image -> image.addPathToFilename(imageBasePath)));
return new ReportDto(reports);
}
throw new ForbiddenException();
Expand All @@ -78,6 +89,10 @@ public ResponseEntity<ReportDto.ReportInfo> getReport(
@RequestAttribute Claims claims) {
if (Role.isAuthorized(claims, Role.MEMBER, Role.ADMIN)) {
Optional<ReportDto.ReportInfo> reportsOr = reportService.getReport(reportId);
reportsOr.ifPresent(report ->
report.getImages().forEach(image ->
image.addPathToFilename(imageBasePath)));

return reportsOr
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
Expand Down Expand Up @@ -153,7 +168,7 @@ public ResponseEntity<List<UserDto.UserMeWithMasking>> getTeamUsers(
content = @Content(
mediaType = "application/json",
examples = @ExampleObject(
value = "{\"imagePath\": \"path/to/image\"}"
value = "{\"imagePath\": \"/path/to/image.png\"}"
)
)
)
Expand All @@ -166,8 +181,8 @@ public ResponseEntity<SingletonMap> uploadImage(
.orElseThrow(UserNotFoundException::new)
.getStudyGroup();

String pathname = imageService.getImagePaths(image, studyGroup.getTag(), reportIdOr);
SingletonMap response = new SingletonMap("imagePath", pathname);
String filename = imageService.getImagePaths(image, studyGroup.getTag(), reportIdOr);
SingletonMap response = new SingletonMap("imagePath", imageBasePath + filename);
return ResponseEntity.ok(response);
}
throw new ForbiddenException();
Expand Down
11 changes: 9 additions & 2 deletions src/main/java/edu/handong/csee/histudy/domain/GroupReport.java
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,18 @@ private void insert(List<String> images) {
this.images.clear();
}
List<Image> paths = images.stream()
.map(img -> new Image(img, this))
.toList();
.map(img -> {
String filename = extractFilenameFromPath(img);
return new Image(filename, this);
}).toList();
this.images.addAll(paths);
}

private String extractFilenameFromPath(String fullPath) {
int lastIndex = fullPath.lastIndexOf('/');
return (lastIndex >= 0) ? fullPath.substring(lastIndex + 1) : fullPath;
}

public boolean update(ReportForm form, List<User> participants, List<GroupCourse> courses) {
this.title = requireNonNullElse(form.getTitle(), this.title);
this.content = requireNonNullElse(form.getContent(), this.content);
Expand Down
6 changes: 5 additions & 1 deletion src/main/java/edu/handong/csee/histudy/dto/ImageDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ public ImageDto(Image entity) {
@Schema(description = "Image ID", example = "1", type = "number")
private long id;

@Schema(description = "Image URL", example = "https://histudy-bucket.s3.ap-northeast-2.amazonaws.com/1.png")
@Schema(description = "Image URL", example = "/path/to/image.png")
private String url;

public void addPathToFilename(String imageBasePath) {
this.url = imageBasePath + this.url;
}
}
4 changes: 4 additions & 0 deletions src/main/java/edu/handong/csee/histudy/dto/ReportDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -100,5 +100,9 @@ public ReportBasic(GroupReport groupReport) {

@Schema(description = "Thumbnail of the report", example = "https://histudy.s3.ap-northeast-2.amazonaws.com/2021-06-01-00-00-00-1")
private String thumbnail;

public void addPathToFilename(String imageBasePath) {
this.thumbnail = imageBasePath + this.thumbnail;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private String saveImage(
MultipartFile image,
String pathname) {
try {
File file = new File(imageBaseLocation + File.separator + pathname);
File file = new File(imageBaseLocation + pathname);
File dir = file.getParentFile();

if (!dir.exists()) {
Expand All @@ -97,7 +97,7 @@ private Optional<String> getSameContent(MultipartFile src, Long reportId) {
try {
return (isUrl(path))
? contentMatches(src, new URL(path))
: contentMatches(src, Path.of(path));
: contentMatches(src, Path.of(imageBaseLocation + path));
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
Expand Down

0 comments on commit dd8965b

Please sign in to comment.