๐ HTML ํผ ์ ์ก์ ํตํด JAVA์์ ํ์ผ ์
๋ก๋ ํ๋ ๊ณผ์ ์ ์ดํด๋ณธ๋ค.
HTML
enctype์ multipart/form-data๋ฅผ ์ ์ธํฉ๋๋ค.
<form id="frm" name="frm" method="post" action="/register/action" enctype="multipart/form-data">
<input type="file" name="file1" />
<input type="file" name="file2" />
<input type="file" name="file3" />
<Button type="submit">Submit</Button>
</form>
Controller
MultipartHttpServletRequest multiRequest๋ฅผ ๋งค๊ฐ๋ณ์๋ก ๋ฐ์ต๋๋ค.
@RequiredArgsConstructor
@Controller
public class BoardController {
private final FileService fileService;
@PostMapping("/register/action")
public void boardRegisterAction(MultipartHttpServletRequest multiRequest) throws Exception {
fileService.uploadFile(multiRequest);
}
}
Service
ํ์ผ์ ์ค์ ๊ฒฝ๋ก์ ์
๋ก๋ํ๋ ๊ณผ์ ์
๋๋ค.
@Service
public class FileService {
public void uploadFile(MultipartHttpServletRequest multiRequest) throws Exception {
// ํ์ผ ์ ๋ณด๋ฅผ ๊ฐ์ผ๋ก ํ๋ Map์ ๊ฐ์ ธ์จ๋ค.
Map<String, MultipartFile> files = multiRequest.getFileMap();
// files.entrySet()์ ์์๋ฅผ ๊ฐ์ ธ์จ๋ค.
Iterator<Map.Entry< String, MultipartFile>> itr = files.entrySet().iterator();
// MultipartFile ์ด๊ธฐํ
MultipartFile mFile = null;
// ํ์ผ์ด ์
๋ก๋ ๋ ๊ฒฝ๋ก๋ฅผ ์ง์
String filePath = "C:\\Users\\venh\\Downloads\\";
// ์ฝ์ด ์ฌ ์์๊ฐ ์์ผ๋ฉด true, ์์ผ๋ฉด false๋ฅผ ๋ฐํ
while (itr.hasNext()) {
// Iterator์ MultipartFile ์์๋ฅผ ๊ฐ์ ธ์จ๋ค.
Map.Entry<String, MultipartFile> entry = itr.next();
// entry์ ๊ฐ์ ๊ฐ์ ธ์จ๋ค.
mFile = entry.getValue();
// ์๋ณธ ํ์ผ๋ช
, ์ ์ฅ ๋ ํ์ผ๋ช
์์ฑ
String fileOrgName = mFile.getOriginalFilename();
if (!fileOrgName.isEmpty()) {
// filePath์ ํด๋น๋๋ ํ์ผ์ File ๊ฐ์ฒด๋ฅผ ์์ฑ
File fileFolder = new File(filePath);
if (!fileFolder.exists()) {
// ๋ถ๋ชจ ํด๋๊น์ง ํฌํจํ์ฌ ๊ฒฝ๋ก์ ํด๋ ์์ฑ
if (fileFolder.mkdirs()) {
System.out.println("[file.mkdirs] : Success");
}
}
File saveFile = new File(filePath, fileOrgName);
// ์์ฑํ ํ์ผ ๊ฐ์ฒด๋ฅผ ์
๋ก๋ ์ฒ๋ฆฌํ์ง ์์ผ๋ฉด ์์ํ์ผ์ ์ ์ฅ๋ ํ์ผ์ด ์๋์ ์ผ๋ก ์ญ์ ๋๊ธฐ ๋๋ฌธ์
// transferTo(File f) ๋ฉ์๋๋ฅผ ์ด์ฉํด์ ์
๋ก๋ ์ฒ๋ฆฌ
mFile.transferTo(saveFile);
}
}
}
}