spring에서 그랬듯 boot에서도 사진입력 시 이미지 파일을 저장해주기 위해서는 MultipartFile를 이용한 아래와같은 별도의 코드를 덧붙여 주어야한다.
//인서트 메서드
@PostMapping("/board/insert")
public String insert(@ModelAttribute BoardDto dto,
@RequestParam MultipartFile upload,
HttpSession session) {
// multipartfile 변수는 form과 일치시켜 준다. 여러장을 넣고싶으면 arraylist필요
//업로드될 실제경로
String realPath=session.getServletContext().getRealPath("/save");
System.out.println(realPath);
String uploadname=upload.getOriginalFilename();
if(upload.isEmpty())
dto.setPhoto("no");
else {
dto.setPhoto(uploadname);
//실제업로드
try {
upload.transferTo(new File(realPath+"\\"+uploadname));
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//db저장
dao.insertboar(dto);
return "redirect:list";
}
//업데이트 메서드
@PostMapping("/board/update")
public String update(@ModelAttribute BoardDto dto,
@RequestParam MultipartFile upload,
HttpServletRequest request) {
// multipartfile 변수는 form과 일치시켜 준다. 여러장을 넣고싶으면 arraylist필요
// HttpServletRequest나 세션이나 똑같음
//업로드될 실제경로
String realPath=request.getServletContext().getRealPath("/save");
System.out.println(realPath);
//기존사진파일명, 새로운 사진파일명
String oldFileName=dao.getData(dto.getNum()).getPhoto();
String newFileNmae=upload.getOriginalFilename();
if(upload.isEmpty())
dto.setPhoto(oldFileName);
else {
dto.setPhoto(newFileNmae);
//기존사진 save파일에서 삭제
deleteFile(realPath, oldFileName);
//실제업로드
try {
upload.transferTo(new File(realPath+"\\"+newFileNmae));
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//db저장
dao.updateboard(dto);
return "redirect:detail?num="+dto.getNum();
}
기존 사진파일에서 다른사진파일로 교체시 기존 사진을 save 폴더에서 삭제하는 메서드
//파일삭제하는 메서드
public void deleteFile(String path, String fileName) {
File file=new File(path+"\\"+fileName);
if(file.exists()) //해당경로에 파일이 있을경우 true
{
file.delete();
System.out.println("파일삭제 성공!!");
}
}
//delete
@GetMapping("/board/delete")
public String delete(@RequestParam Long num,
HttpServletRequest request) {
String path=request.getServletContext().getRealPath("/save");
String filename=dao.getData(num).getPhoto();
//사진삭제
deleteFile(path, filename);
//db에서도 삭제
dao.deleteboard(num);
return "redirect:list";
}
파일삭제하는 메서드를 별도로 만들어 데이터파일을 이미지 폴더에서 삭제 후 db에서 삭제.