본문 바로가기
Code/Web

[JSP Code] 외부 라이브러리 없이 파일 업로드하기

by 스응 2023. 4. 6.
728x90
728x90

코드

#  JSP - form

1
2
3
4
5
6
7
                                               <!-- 중요 !! -->
<form action="uploadProc" method="post" enctype="multipart/form-data">
    <label for="file">Choose a file : </label>
    <input type="file" name="file" id="file">
    <br>
    <input type="submit" value="파일 업로드">
</form>
cs

 

#  서블릿

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@WebServlet("/upload")
@MultipartConfig // <- 중요 !!!!!
public class UploadController extends HttpServlet {
 
    ...
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 파일 업로드 처리
        Part filePart = request.getPart("file"); // input의 name을 매개변수로
 
        // 확인하기
        System.out.println("컨텐츠 확인 (마임 타입) : " + filePart.getContentType()); 
        System.out.println("바이트 기반 파일 크기 : " + filePart.getSize());
        System.out.println("업로드된 파일 이름 : " + filePart.getSubmittedFileName());
        
        // 입력 스트림 준비
        InputStream fileContent = filePart.getInputStream();
 
        // 출력 스트림 준비 (내 서버 컴퓨터에 파일을 저장할 예정)
        OutputStream outputStream = null// 예외 처리를 위해 null 처리 먼저
        
        // 같은 이름의 파일을 여러 번 올린다면 구분할 수 없기 때문에, 랜덤한 문자열을 앞에 붙여서 구분
        try {
            // 랜덤 문자열 생성
            UUID uuid = UUID.randomUUID();
            // 랜덤 문자열 + 기존 파일명
            String fileName = uuid + "_" + filePart.getSubmittedFileName(); 
            
            // 파일을 저장할 폴더를 코드 상으로 생성하기
            String saveDirectory = "C:/폴더명";
            File dir = new File(saveDirectory);
 
            // dir 안에 파일이 하나도 없다면 폴더가 만들어지지 않은 것
            if (!dir.exists()) {
                dir.mkdirs(); // 폴더 생성
            }
            
            File file = new File("C:/폴더명/", fileName); // 해당 경로에 fileName 변수에 담긴 이름으로 파일을 생성할 것
            
            // 출력 스트림 사용
            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024]; // 1 KB == 1024 byte
            int length;
            while ((length = fileContent.read(buffer)) != -1) {
                // 1024 바이트씩 읽음
                outputStream.write(buffer, 0length); 
            }
            
        } catch (Exception e) {
            
        } finally {
            outputStream.flush(); // flush() 하지 않으면 데이터가 전송되지 않음
 
            // 폴더가 없을 경우 예외가 발생하기 때문에 방어적 코드 필요
            if (outputStream != null) {
                outputStream.close(); // 출력 스트림 닫기
            }
            fileContent.close(); // 입력 스트림 닫기
            response.sendRedirect("/demo12/home.jsp");
 
        }
    }
 
}
 
 
cs

 

  -  getPart() 메서드는 멀티 파트 폼 데이터를 처리하기 위해 사용됨

      → 멀티 파트 폼 데이터

           : HTTP 요청 메시지의 body에 있는 여러 개의 파트로 구성된 데이터

320x100
반응형

댓글