2021. 12. 9. 12:57ㆍ스프링부트
사진 업로드 시 저장을 프로젝트 내부에 하게되면 재배포시 파일이 날아갈 수 있으니 외부 경로에 저장 할 수 있게 합니다
외부 경로 설정을 위해 config패키지에 설정파일을 추가합니다
@Configuration public class WebConfig implements WebMvcConfigurer { @Value("${resource.path}") private String resourcePath; @Value("${upload.path}") private String uploadPath; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(uploadPath) .addResourceLocations(resourcePath); } }
uploadPath로 요청이 들어오면 resourcePath에서 찾겠다는 의미입니다
공통적으로 사용될 경로이므로 application.properties에 지정해 놓고 불러 쓸 수 있도록 하겠습니다
application.properties에 추가
#/upload 로 요청이 들어오면 resource.path에서 찾기 resource.path=file:///C:/resource/ upload.path=/upload/** #이미지 파일 업로드 위치 resource=C:/resource spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB
저는 C: 아래에 resource라는 이미지를 관리 할 폴더를 생성하고 이미지를 찾을 경로와 이미지를 저장할 경로, 이미지 최대용량을 설정했습니다
uil패키지에 UploadFile클래스를 생성합니다
package com.baemin.util; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.util.Calendar; import java.util.UUID; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.util.FileCopyUtils; import org.springframework.web.multipart.MultipartFile; @Component public class UploadFile { @Value("${resource}") private String path; public String makeDir() { Calendar cal = Calendar.getInstance(); String yearPath = File.separator +cal.get(Calendar.YEAR) + ""; String monthPath = yearPath + File.separator + new DecimalFormat("00").format(cal.get(Calendar.MONTH) + 1); String datePath = monthPath + File.separator + new DecimalFormat("00").format(cal.get(Calendar.DATE)); if(!new File(path+datePath, datePath).exists()) { new File(path, yearPath).mkdir(); new File(path, monthPath).mkdir(); new File(path, datePath).mkdir(); } return datePath; } public String fildUpload(MultipartFile file) throws IOException { UUID uuid = UUID.randomUUID(); String fileName = File.separator + uuid + "_" + file.getOriginalFilename(); String dir = makeDir(); File uploadFile = new File(path + dir, fileName); uploadFile.createNewFile(); FileCopyUtils.copy(file.getBytes(), uploadFile); return File.separator + "upload" + dir + fileName; } }
makeDir()은 path로 설정한 경로 아래에 현재시각을 이름으로 폴더를 생성합니다 ex) 2021/12/09
fildUpload()의
File uploadFile = new File(path + dir, fileName);
uploadFile.createNewFile();
makeDir()로 생성한 폴더 아래에 uuid로 랜덤한 문자를 생성 후 파일의 원래 이름을 더해 빈 파일을 생성합니다
빈 파일에 파일정보를 저장할 땐 FileCopyUtils.copy 또는 MultipartFile클래스의 transferTo를 사용해 저장 할 수 있습니다
이후 db에 파일의 경로를 저장하기 위해 파일경로+이름을 반환합니다
StoreController상단에 UploadFile을 주입받을 수 있도록 추가합니다
@Autowired private UploadFile uploadFile;
리뷰작성과 리뷰수정 메서드를 수정합니다
// 리뷰 작성 @PostMapping("/store/review") public String review(Review review, MultipartFile file, @AuthenticationPrincipal LoginService user) throws IOException { if (file.isEmpty()) { String img = ""; review.setReviewImg(img); } else { String img = uploadFile.fildUpload(file); review.setReviewImg(img); } long userId = user.getUser().getId(); review.setUserId(userId); storeService.reviewWrite(review); return "redirect:/orderList"; } // 리뷰 수정 @PostMapping("/store/reviewModify") public String reviewModify(Review review, MultipartFile file, @AuthenticationPrincipal LoginService user) throws IOException { if(!file.isEmpty()){ String img = uploadFile.fildUpload(file); review.setReviewImg(img); } long userId = user.getUser().getId(); review.setUserId(userId); storeService.reviewModify(review); return "redirect:/orderList"; }
사진 첨부 후 가게에 리뷰 사진이 올라간 걸 볼 수 있습니다


-- 배달 완료 시 댓글 가능으로 변경
-- 사진 여러장 첨부 아직 미구현
'스프링부트' 카테고리의 다른 글
스프링부트+jsp로 배달사이트 만들기-17 xss 방어하기 (0) | 2021.12.09 |
---|---|
스프링부트+jsp로 배달사이트 만들기-18 주문상세 페이지 (0) | 2021.12.09 |
스프링부트+jsp로 배달사이트 만들기-15 리뷰작성 (0) | 2021.12.08 |
스프링부트+jsp로 배달사이트 만들기-14 주문완료 (6) | 2021.12.08 |
스프링부트+jsp로 배달사이트 만들기-12 가게 정보 탭 (0) | 2021.12.07 |