본문 바로가기
카테고리 없음

파일 업로드 처리하기

by 그리득 2023. 12. 13.
728x90

 

 

pom.xml에 라이브러리 등록

 

파일업로드 라이브러리 등록하기
1.common-io 버전 2.7
2.commons-fileupload 버전 1.4

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

 

servlet-context.xml에 resolver 등록하기

 

<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<beans:property name="maxUploadSize" value="104857600"/>
</beans:bean>

 

104857600=100mb

 

 

jsp form태그에 enctype 추가

 

enctype="multipart/form-data"

 

 

클래스에 파라미터 값으로 MultipartFile 받기

 

@PostMapping("/boardWriteend.do")
								//업로드 파일 여러개 가져올 땐 배열로
public String boardWriteend(MultipartFile [] upFile
						,HttpSession session) {
		
	//MultipartFile객체를 이용해서 파일 저장하기
	//MultipartFile객체가 제공하는 transferTo()메소드를 이용
	//1. 저장할 위치 -> 절대경로
	String path=session.getServletContext().getRealPath("/resources/upload/board");
		
	//2. 파일 이름을 재정의 -> renamedFile name을 설정 -> 중복되지않게 설정
	//파일명을 재정의 로직을 구성하기(rename은 확장자명을 뺀 이름)
	//getRealPath=webapp부터 시작

	List<Attachment> files=new ArrayList<Attachment>();
		
	if(upFile!=null) {
		for(MultipartFile mf:upFile) {
        //단일로 받아올 땐 upFile 그대로
//		if(!upFile.isEmpty()) {
		if(!mf.isEmpty()) {
//		String oriName=upFile.getOriginalFilename();
		String oriName=mf.getOriginalFilename();
		//확장자명
		String ext=oriName.substring(oriName.lastIndexOf("."));
		//String으로 바꿀려고 util로 가져옴 simpledateformat이 util로만 가능해서
		Date today=new Date(System.currentTimeMillis());
		int randomNum=(int)(Math.random()*10000)+1;
		String rename="rocket_"+(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(today))+"_"+randomNum+ext;
		try {
//			upFile.transferTo(new File(path,rename));
			mf.transferTo(new File(path,rename));
			Attachment file=Attachment.builder()
						.originalFilename(oriName)
						.renamedFilename(rename)
						.build();
			//파일 리스트에 추가
			files.add(file);
			} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}