어떻게 이미지 파일을 관리해야 할까 ?
- 1. img1 column을 만들어서, img1 VARCHAR(100) 이런 식으로 구성
- 만약 파일 수가 많아지면 , column 여러 개 추가 ? 음... 비효율적인데
- 2. create TABLE articleFile => article 테이블과 1:N 관계. N이 파일 여러 개를 말함.
- articleFile, memberFile, boardFile .... -> 음.. 비효율적인데
- 그냥 모두를 포괄할 수 있는 (공통으로 사용하는)file 하나로 만들기. -> **GenFile** (업로드나, 다운로드를 통해서 만든 파일이라는 뜻)
- GenFile 에서 article, member, board 에 대한 이미지 파일들을 관리하도록 설계하자!
이미지 업로드 폼 작성
<form th:action="@{/upload}" method="POST" enctype="multipart/form-data">
<div>
<span>파일 1</span>
<input type="file" name="img1" accept="image/png, image/gif, image/jpeg">
</div>
<div>
<span>파일 2</span>
<input type="file" name="img2" accept="image/png, image/gif, image/jpeg">
</div>
<div>
<span>업로드</span>
<input type="submit" value="전송">
</div>
</form>
method="POST" enctype="multipart/form-data"
는 파일 업로드 시 반드시 필요한 폼 속성이다.
DB에 업로드 한 파일 저장하기
@Controller
@RequestMapping("/upload")
public class FileUploadController {
@Value("${custom.genFileDirPath}")
private String genFileDirPath;
@RequestMapping("")
@ResponseBody
public String upload(@RequestParam("img1") MultipartFile img1, @RequestParam("img2") MultipartFile img2) {
try {
img1.transferTo(new File(genFileDirPath + "/1.png"));
img2.transferTo(new File(genFileDirPath + "/2.png"));
} catch (IOException e) {
throw new RuntimeException(e);
}
return "업로드 완료!";
}
}
- @RequestParam 으로 폼의 input 태그의 name 속성 값이 바인딩된다.
- String genFileDirPath; 라는 변수로 아래 yml 설정에서 custom 정보에 쓰여 있는 파일 경로를 저장한다.
...
custom:
genFileDirPath: c:/temp/app10