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

2023. 4. 6. 19:31·Java/JSP
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>
Colored by Color Scripter
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, 0, length); 
            }
            
        } catch (Exception e) {
            
        } finally {
            outputStream.flush(); // flush() 하지 않으면 데이터가 전송되지 않음
 
            // 폴더가 없을 경우 예외가 발생하기 때문에 방어적 코드 필요
            if (outputStream != null) {
                outputStream.close(); // 출력 스트림 닫기
            }
            fileContent.close(); // 입력 스트림 닫기
            response.sendRedirect("/demo12/home.jsp");
 
        }
    }
 
}
 
 
Colored by Color Scripter
cs

 

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

      → 멀티 파트 폼 데이터

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

320x100
반응형
저작자표시 비영리 변경금지 (새창열림)

'Java > JSP' 카테고리의 다른 글

[JSP] 웹 컨테이너 (Web Container)  (0) 2023.06.18
[JSP] 파일 업로드 및 조회  (0) 2023.04.06
[JSP] 필터 (Filter)  (0) 2023.04.06
[JSP] 쿼리 파라미터 방식 (쿼리 스트링)  (0) 2023.04.05
[JSP] Java web으로 SQL CRUD 구현하기  (0) 2023.03.28
'Java/JSP' 카테고리의 다른 글
  • [JSP] 웹 컨테이너 (Web Container)
  • [JSP] 파일 업로드 및 조회
  • [JSP] 필터 (Filter)
  • [JSP] 쿼리 파라미터 방식 (쿼리 스트링)
스응
스응
    반응형
    250x250
  • 스응
    이서영의 개발 블로그
    스응
  • 전체
    오늘
    어제
  • 글쓰기 관리
    • 분류 전체보기 (385)
      • Java (134)
        • Base (54)
        • Spring Boot (37)
        • JSP (16)
        • Swing (GUI) (20)
        • Design Pattern (7)
      • C# (13)
      • PHP (18)
      • SQL (27)
      • Vue.js (9)
      • Tailwind CSS (4)
      • TypeScript (7)
      • HTML & CSS (27)
      • JavaScript (26)
      • jQuery (10)
      • Android (3)
      • - - - - - - - - - - - - - - (0)
      • Hotkeys (5)
      • CS (30)
      • IT Notes (13)
      • Error Notes (17)
      • Team Project (24)
        • Airlines Web Project (12)
        • University Web Project (6)
        • Strikers 1945 GUI Project (6)
      • My Project (18)
        • Library Web Project (8)
        • Pet Shopping Mall GUI Project (10)
      • etc. (0)
  • 블로그 메뉴

    • Home
    • Write
  • 링크

    • 깃허브
  • 공지사항

  • 인기 글

  • 태그

    면접
    SWAGGER
    php
    vuejs
    Wordpress
    jsp
    SEO
    Codeigniter
    Hotkeys
    오블완
    js
    errorNote
    typeScript
    zapier
    C#
    http
    tailwindcss
    SpringBoot
    티스토리챌린지
    Swing
    SQL
    CSS
    jQuery
    git
    개발일지
    HTML
    cs
    Android
    java
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.0
스응
[JSP] 외부 라이브러리 없이 파일 업로드하기
상단으로

티스토리툴바