JSP는 대부분의 기능을 오픈 소스로 제공하며, 대표적인 기능이 파일 업로드와 다운로드 기능이고, 이 외에도 이메일 등 많은 오픈 소스 라이브러리를 제공한다.
파일 업로드 기능을 사용하기 위해서는 오픈 소스 라이브러리를 설치해야 한다.
http://archive.apache.org/dist/commons/fileupload/binaries/
Index of /dist/commons/fileupload/binaries
archive.apache.org
https://commons.apache.org/proper/commons-io/download_io.cgi
Commons IO – Download Apache Commons IO
Download Apache Commons IO Using a Mirror We recommend you use a mirror to download our release builds, but you must verify the integrity of the downloaded files using signatures downloaded from our main distribution directories. Recent releases (48 hours)
commons.apache.org
위의 사이트에서 2개를 다운받고 압축을 푼 다음 파일이름과 버전만 적혀있는 jar 파일을 프로젝트의 lib에 복사한다.
JSP에서 파일 업로드
파일 업로드 라이브러리에서 제공하는 클래스에는 DiskFileItemFactory, ServletFileUpload가 있다.
DiskFileItemFactory
메서드 | 기능 |
setRepository() | 파일을 저장할 디렉토리 설정 |
setSizeThreadhold() | 최대 업로드 가능한 파일 크기를 설정 |
ServletFileUpload
메서드 | 기능 |
parseRequest() | 전송된 매개변수를 List 객체로 얻음 |
getItemIterator() | 전송된 매개변수를 Iterator 타입으로 얻음 |
파일 업로드를 처리하는 서블릿 클래스를 아래와 같이 작성한다.
라이브러리에서 제공하는 DiskFileItemFactory 클래스를 이용해 저장 위치와 업로드 가능한 최대 파일 크기를 설정한다.
그리고 ServletFileUpload 클래스를 이용해 파일 업로드 창에서 업로드 된 파일과 매개변수에 대한 정보를 가져와 파일을 업로드하고, 매개변수 값을 출력한다.
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
67
68
69
70
71
72
73
74
75
76
77
|
package sec01.ex01;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/upload.do")
public class FileUpload extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doHandle(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doHandle(request,response);
}
private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
request.setCharacterEncoding("utf-8");
String encoding="utf-8";
File currentDirPath = new File("c:\\programming/file_repo");//업로드할 파일 경로 지정
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(currentDirPath);//파일 경로 설정
factory.setSizeThreshold(1024*1024);//최대 업로드 가능한 파일 크기 설정
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);//request 객체에서 매개변수를 List로 가져옴
for (int i = 0; i < items.size(); i++) {
FileItem fileItem = (FileItem) items.get(i);//파일 업로드창에서 업로드된 항목들을 하나씩 가져옴
//폼 필드면 전송된 매개변수 값을 출력
if (fileItem.isFormField()) {
System.out.println(fileItem.getFieldName()+"="+fileItem.getString(encoding));
}
//폼 필드가 아니면 파일 업로드 기능울 수행
else {
System.out.println("매개변수명"+fileItem.getFieldName());
System.out.println("파일이름"+fileItem.getName());
System.out.println("파일크기"+fileItem.getSize()+"bytes");
//업로드한 파일 이름 가져옴
if (fileItem.getSize() > 0) {
int idx = fileItem.getName().lastIndexOf("\\");
if (idx == -1) {
idx = fileItem.getName().lastIndexOf("/");
}
String fileName = fileItem.getName().substring(idx+1);
//업로드한 파일 이름으로 저장소에 파일을 업로드
File uploadFile = new File(currentDirPath+"\\"+fileName);
fileItem.write(uploadFile);
}//end if
}//end if
}//end for
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
cs |
이렇게 하면 성공적으로 내가 지정한 경로에 파일이 업로드 되게 되고, 콘솔창에서도 해당 파일과 매개변수의 정보가 다 출력되는 것을 확인할 수 있다.
JSP에서 파일 다운로드
이번에는 서블릿 기능을 이용해 업로드한 파일을 다운로드하는 예제다.
first.jsp를 위와 같이 작성하며, 여기서는 다운로드할 이미지 파일 이름을 result.jsp로 전달한다.
result.jsp를 위와 같이 작성한다.
이미지 태그의 src 속성에 다운로드를 요청할 서블릿 이름과 파일 이름을 GET 방식으로 전달한다.
다운로드한 이미지 파일을 바로 이미지 태그에 표시하고, <a>태그를 클릭해 서블릿에 다운로드를 요청하면 파일 전체를 로컬 PC에 다운로드 한다.
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
|
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/download.do")
public class FileDownload extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doHandle(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doHandle(request,response);
}
private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
String file_repo="C:\\programming/file_repo";//파일을 올리는 폴더 경로
String fileName = (String)request.getParameter("fileName");//매개변수로 전송된 파일 이름을 읽어옴
System.out.println("fileName="+fileName);
OutputStream out = response.getOutputStream();//response에서 OutputStream 객체를 가져옴
String downFile = file_repo+"\\"+fileName;
File f = new File(downFile);
//파일을 다운로드할 수 있음
response.setHeader("Cache-Control", "no-cache");
response.addHeader("Content-disposition", "attachment; fileName="+fileName);
FileInputStream in = new FileInputStream(f);
//버퍼 기능을 이용해 파일에서 버퍼로 데이터를 읽어와 한꺼번에 출력
byte[] buffer = new byte[1024*8];
while (true) {
int count = in.read(buffer);
if (count == -1) {
break;
}
out.write(buffer,0,count);
}
in.close();
out.close();
}
}
|
cs |
파일 다운로드 기능을 할 서블릿인 FileDownload 클래스를 다음과 같이 작성한다.
파일 다운로드 기능은 자바 IO를 이용해 구현한다.
먼저 response.getOutputStream();을 호출해 OutputStream을 가져온다. 그리고 배열로 버퍼를 만든 후 while문을 이용해 파일에서 데이터를 한번에 8kb씩 버퍼에 읽어온다.
이어서 OutputStream의 write() 메서드를 이용해 다시 브라우저로 출력한다.
'자바 웹 > jsp' 카테고리의 다른 글
JSP 표준 태그 라이브러리(JSTL) (0) | 2022.06.19 |
---|---|
표현 언어 (0) | 2022.06.18 |
액션 태그 (0) | 2022.05.15 |
JSP 스크립트 요소 기능 (0) | 2022.05.14 |
JSP 정의와 구성요소 (0) | 2022.05.14 |