이미지 파일 업로드, DB에 파일 저장하기

Ryu·2022년 9월 6일
0

어떻게 이미지 파일을 관리해야 할까 ?

- 1. img1 column을 만들어서, img1 VARCHAR(100) 이런 식으로 구성 
	- 만약 파일 수가 많아지면 , column 여러 개 추가 ?... 비효율적인데
- 2. create TABLE articleFile => article 테이블과 1:N 관계. N이 파일 여러 개를 말함.
	- articleFile, memberFile, boardFile .... ->.. 비효율적인데
	- 그냥 모두를 포괄할 수 있는 (공통으로 사용하는)file 하나로 만들기.  -> **GenFile** (업로드나, 다운로드를 통해서 만든 파일이라는 뜻)
	- GenFile 에서 article, member, board 에 대한 이미지 파일들을 관리하도록 설계하자! 

이미지 업로드 폼 작성

// upload.html  
<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 정보에 쓰여 있는 파일 경로를 저장한다.
// application.yml
...
custom:
  genFileDirPath: c:/temp/app10
profile
Strengthen the core.

0개의 댓글