프로젝트 정리/지역기반 모임 서비스

이미지 업로드 직후 업로드한 이미지가 보이지 않는 상황 해결

게시글을 작성한 후 파일을 서버 내부 폴더에 저장하고 게시글 목록을 동기적으로 이동했을때

이미지가 나오지 않는 상황이 발생하였다.

 

원인은 서버 내부 폴더를 새로고침 하여야 해당 파일이 반영된다는 점이었다.

정적리소스 서버 재시작 없이 바로 반영하기 등의 키워드로 구글링을 해보고 설정을 해봤지만

결국 폴더를 새로고침 해야 반영되는 상황이 계속 되었다.

 

비동기적으로 해당 파일을 가져오는 방법으로 해결하였다.

이하는 해결한 비동기 코드이다.

 

package com.example.batisproject.apicontroller.user;

import lombok.extern.slf4j.Slf4j;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

@Slf4j
@RestController
public class GatherApiController {

    @Value("${kr.co.unstoppable.upload.path}")
    private String uploadPath;

    @Operation(summary = "myGather Image View method", description = "내 모임 이미지를 가져오는 method")
    @GetMapping("/user/myGather/{fileName}")
    public ResponseEntity<Resource> viewMyGatherFile(@PathVariable String fileName) {

        return getResourceResponseEntity(fileName);
    }

    @Operation(summary = "gather Image View method", description = "모임 이미지를 가져오는 method")
    @GetMapping("/user/gather/{fileName}")
    public ResponseEntity<Resource> viewGatherFile(@PathVariable String fileName) {

        return getResourceResponseEntity(fileName);
    }

    private ResponseEntity<Resource> getResourceResponseEntity(@PathVariable String fileName) {
        Resource resource = new FileSystemResource(uploadPath + File.separator + fileName);

        String resourceName = resource.getFilename();
        HttpHeaders headers = new HttpHeaders();

        try {
            headers.add("Content-Type", Files.probeContentType( resource.getFile().toPath() ));
        } catch (IOException e){
            return ResponseEntity.internalServerError().build();
        }

        return ResponseEntity.ok().headers(headers).body(resource);
    }

}

 

@GetMapping("/user/myGather")
    public String myGatherList(@RequestParam(value = "category", required = false, defaultValue = "")Integer category,
                               @RequestParam(value = "viewMode", required = false, defaultValue = "")String viewMode,
                               Model model, @CurrentUser User user,
                               @Valid PageRequestDTO pageRequestDTO,
                               BindingResult bindingResult) {


        UserDTO userDTO = userService.existsByEmail(user.getUsername());
        List<CategoryDTO> categoryList = categoryService.getAllMainCategory();
        PageRequestDTO revisedPageDTO = setKeyword(pageRequestDTO, bindingResult, userDTO, category);
        PageResponseDTO<GatherResponseDTO> gatherList = gatherService.getAllMyList(revisedPageDTO);
        LocationDTO locationDTO = locationService.getByUsername(userDTO.getUsername());

        addModel(category, viewMode, model, categoryList, gatherList, locationDTO, userDTO);
        return "gather/myGatherList";
    }

 

thymeleaf

<img class="img-fluid"
style="width: 620px; height: 300px"
th:if="${gatherList.dtoList.get(num * 2).getSaveFileName() != null}"
th:src="|/user/myGather/${gatherList.dtoList.get(num * 2).saveFileName}|"
/>
<img alt="100%x280"
class="img-fluid" src="https://via.placeholder.com/620x300/000000/FFFFFF?text=No+Image"
th:if="${gatherList.dtoList.get(num * 2).getSaveFileName() == null}">

 

저장하는 파일 폴더를 서버 외부에 두면 서버 새로고침 없이도 이미지가 바로 반영될 듯 하다.

다음에 이미지 관련 기능 작업시 시도해보자.