Backend/JSP Servlet

File upload with input tag

brian110326 2024. 3. 26. 21:04

<div class="form-group row">
          <label for="file" class="col-sm-2 col-form-label">파일첨부</label>
          <div class="col-sm-10">
            <input type="file" name="attatch" id="file" />
            <small class="text-muted" id="file">(파일크기 : 2MB)</small>
          </div>
        </div>

게시판을 작성하면 글 뿐 아니라 다양한 파일들을 업로드 시킬 수 있다. 이럴 때  input 태그 안에 있는 name요소를 이용하여  request 객체와 함께 getParameter로 입력값을 담을 수 있다. 하지만 파일 업로드시 request 객체를 사용할 수 없다.

 

파일 업로드 처리

1) 외부 라이브러리 사용 => Apache Commons FileUpload

2) Servlet 에서 제공되는 것을 사용

 

파일을 업로드 시 반드시 form 태그안에 enctype을 넣어야한다. 이 때 enctype은 encoding type이라 할 수 있다.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/enctype

 

HTMLFormElement: enctype property - Web APIs | MDN

The HTMLFormElement.enctype property is the MIME type of content that is used to submit the form to the server. Possible values are:

developer.mozilla.org

enctype

1) application/x-www-form-urlencoded : 기본값

2) multipart/form-data : input file type이 존재할 때

 

현재 파일을 업로드하는 input태그가 있기 때문에 2번 방법으로 해볼 수 있다. form 태그안에 enctype과 2번을 넣어주면 된다.

<form action='<c:url value="/qWrite.do" />' method="post" role="form" id="writeForm" enctype="multipart/form-data">

 

또한 controller에서 파일 업로드를 위한 어노테이션( @MultipartConfig )을 작성해야한다. 

@MultipartConfig(maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5) 

- maxFileSize : 개별 파일의 용량 : 1024 * 1024 * 5 ==> 5MB

- maxRequestSize : 개별 파일의 용량 + 쿠키 , 세션 등 요청 시 추가적으로 붙는 총 용량

'Backend > JSP Servlet' 카테고리의 다른 글

Connection객체와 getConnection()메소드  (0) 2024.03.21
Model1, Model2  (0) 2024.03.21
Session  (0) 2024.03.15
JSP 내장객체 HttpSession  (0) 2024.03.15
JSP 기본코드  (0) 2024.03.14