본문 바로가기

Spring Boot

파일 첨부(전송, 받기)

클라이언트 파일 -> 서버로 전송 (파일첨부)

 

1. HTML 파일 전송 form 작성

<form action="경로" method="post" enctype="multipart/form-data">
    <input type="file" name="upload">
    <input type="submit" value="전송">
</form>

<%--
파일 전송 form 요소
method = "post"
enctype="multipart/form-data"
이 두개가 필수
이유: 파일 크기나 길이가 긴 경우 get로는 한계가 있을 수 있어 post방식으로 전송
multipart 이유는 파일은 텍스트 정보가 아닐 수 있어서 추가
--%>

 

2. 컨트롤러에서 받을 때 타입은 MultipartFile 타입으로 받는다.

 

3. 저장할 경로,파일관리에 용이하게 저장시킬 파일명 형식(오늘날짜_파일명)을 지정

 

4. InputStream, FileOutputStream 으로 클라이언트가 보낸 파일을 읽고 서버에 저장시킨다.

 

예시)

@PostMapping("경로")
public void method4(MultipartFile upload) throws Exception{
	
    // 파일명 얻기
    String fileName = upload.getOriginalFilename();
    // 경로 설정
    String path = "C:\\Temp\\CodeStudy\\" + "231020_upload_" + fileName;
	
    // InputStream 으로 파일 받기
    InputStream is = upload.getInputStream();
    // FileOutputStream으로 서버로 내보내기
    FileOutputStream os = new FileOutputStream(path);
	
    // Buffered로 성능 향상
    BufferedInputStream bis = new BufferedInputStream(is);
    BufferedOutputStream bos = new BufferedOutputStream(os);

	// Input,Output은 try catch문 작성해야함
	try(is; os; bis; bos;){
    
    	// 바이트 크기 지정
        byte[] bytes = new byte[1024];
		
        // 읽은 데이터의 크기 변수선언
        int len = 0;
		
        // 반복문으로 데이터 내보내기
        // 더 내보낼 데이터가 없으면 read메소드는 -1을 return
        while ((len = bis.read(bytes)) != -1) {
            bos.write(bytes, 0, len);
        }
		
        // 혹시 모를 잔여 데이터를 내보내야하니깐 flush()
        bos.flush();
    }

}

MultipartFile 클래스의 메소드들

getOriginalFilname() - 파일명 가져오기

getSize() - 파일크기

getInputStream - InputStream으로 가져오기

getBytes - Bytes확인 가능

더 자세한 내용 및 추가 메소드 들은 api문서 확인


파일 여러개 첨부(클라이언트 -> 서버)

1. 파일전송 form안 <input type="file"> 속성에 multple 추가

<input type="file" multiple name="files">

 

2. 컨트롤러에서는 MultipartFile배열 형태로 받아준다.

 

3. 배열로 받을 때 주의 사항은 length()로 파일의 유무를 확인 할 때   파일이 첨부 되지 않아도 1로 시작되기 때문에 1로 나온다. (3개면 3)

 

4. MultipartFile클래스에 있는 getSize() 메소드를 이용해 size로 파일 유무 확인 (없으면 0)

 

5. 반복문으로 배열로 받은 파일을 하나씩 서버에 저장시키면된다.

 

예시)

@PostMapping("경로")
public void method6(MultipartFile[] files) throws IOException {
   
    // 반복문으로 여러 파일을 한 파일씩 처리
    for (MultipartFile file : files) {
    
        // 파일의 크기로 파일 유무 확인
        if (file.getSize() > 0) {
        	
            // 경로 설정
            String path = "C:\\Temp\\CodeStudy\\";
            
            // Bufferd로 바로 작성해도 된다 (코드가 줄어드는 장점)
            BufferedInputStream bis = new BufferedInputStream(file.getInputStream());
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + file.getOriginalFilename()));
			
            // try-catch문
            try (bis; bos;) {
            
            	// byte 크기 지정
                byte[] data = new byte[1024];
                // 반복문으로 데이터 내보내기
				// 더 내보낼 데이터가 없으면 read메소드는 -1을 return
                int len = 0;
                while ((len = bis.read(data)) != -1) {
                    bos.write(data, 0, len);
                }
                // 혹시 모를 잔여 데이터를 내보내야하니깐 flush()
                bos.flush();
            }
        }
    }
}
반응형