파일 첨부를 하려면 일단 multipartFile이라는 애를 씀.
그럴려면 servlet.xml에서 multipartResolver라는 애를 등록해줘야 됨.
첨부 사이즈도 정할 수 있고 버전 올라가면 개별 파일 사이즈도 정할 수 있는 것 같음.
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="52428800"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
그다음 pom.xml에 얘도 있어야 됨.
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>버전 아무거나</version>
</dependency>
컨트롤러
@RequestMapping(value = "알아서", method = RequestMethod.POST)
public String postFileRegister(@RequestParam("files") MultipartFile[] files) {
try {
fileService.registerFile(files);
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:원하는 경로";
}
배열로 받던 리스트로 받던 알아서 편하게 받아서
for문 돌려서 꺼내서 하나씩 db 저장하니까 잘 동작했다.
서비스
private static final String UPLOAD_DIR = "C:/upload"; 위에 선언해줘야댐
@Override
public void registerFile(MultipartFile[] files) throws Exception {
if(file != null && files.length > 0) {
for(MultipartFile f : files ) {
if(!f.isEmpty()) {
String filePath = Paths.get(UPLOAD_DIR, originalFileName).toString();
f.transferTo(new File(filePath));
// DB에 저장하는 로직..
}
}
}
나중엔 한번에 저장하는걸 해봐야지
'Spring > MVC' 카테고리의 다른 글
# Spring Boot - POI로 엑셀 다운로드 기능 만들기 (maven) (1) | 2025.06.04 |
---|---|
# Entity - @GeneratedValue 전략 정리 (JPA + postgreSQL 기준) (0) | 2025.05.29 |
# java - 예외처리 @Valid (1) | 2025.05.27 |
# 프론트엔드와 백엔드에서 각각 시간 포맷 처리하는 이유 (Spring Boot + JS) (0) | 2025.05.12 |
# FileInputStream - 파일 다운로드 처리 (0) | 2025.02.17 |