JSP 파일업로드, 다운로드

파일 업로드, 다운로드에 필요한 라이브러리 jar

commons-fileupload-1.4.jar
0.07MB
commons-io-2.8.0.jar
0.27MB

 

-----------------------------------------------------------------------------------------------------------------------------------

파일업로드

uploadForm.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8"
isELIgnored="false"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("utf-8");
%>
<c:set var="context" value="${pageContext.request.contextPath}" scope="page"></c:set>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="${context}/upload.do" method="post" enctype="multipart/form-data">
		파일1: <input type="file" name="file1" id="" /> <br />
		파일2: <input type="file" name="file2" id="" /> <br /> 
		매개변수 1: <input type="text" name="param1" id="" /><br />
		매개변수 2: <input type="text" name="param2" id="" /><br />
		매개변수 3: <input type="text" name="param3" id="" /><br />
		<input type="submit" value="전송" />
	</form>
</body>
</html>

 

FileUpload.java (서블릿)

request.setCharacterEncoding("utf-8");
		String encoding="utf-8";
		File currentFileDir = new File("C:\\file_repo");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(currentFileDir);
		factory.setSizeThreshold(1024*1024);
		
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			for(int i = 0; i < items.size(); i++) {
				FileItem fileItem = (FileItem) items.get(i);
				if(fileItem.isFormField()) {
					System.out.println(fileItem.getName() + " = " + fileItem.getString(encoding));
				}else {
					System.out.println("매개변수 이름 : " + fileItem.getFieldName());
					System.out.println("파일 이름 : " + fileItem.getName());
					System.out.println("파일 크기 : "+fileItem.getSize());
					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(currentFileDir + "\\" + fileName);
						fileItem.write(uploadFile);
					}
				}
			}

 

 

-----------------------------------------------------------------------------------------------------------------------------------

 

파일다운로드

 

first.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="result.jsp" method="post">
		<input type="hidden" name="param1" value="anne-sack-yq-L77K8Ia4-unsplash.jpg" />
		<input type="hidden" name="param2" value="morgane-le-breton-QbLTpyf3QoU-unsplash.jpg" />
		<input type="submit" value="이미지 다운로드" />
	</form>
</body>
</html>

 

 

resulut.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	isELIgnored="false"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
	request.setCharacterEncoding("utf-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<c:set var="file1" value="${param.param1}"></c:set>
<c:set var="file2" value="${param.param2}"></c:set>
<title>Insert title here</title>
</head>
<body>
매개변수1 : <c:out value="${file1}"></c:out> <br />
매개변수2 : <c:out value="${file2}"></c:out> <br />

<c:if test="${not empty file1}">
	<img src="${contextPath}/download.do?fileName=${file1}" width="300" height="300" alt="" /><br />
</c:if>
<br />
<c:if test="${not empty file2}">
	<img src="${contextPath}/download.do?fileName=${file2}" width="300" height="300" alt="" /><br />
</c:if>
파일 내려받기 : <br />
<a href="${contextPath}/download.do?fileName=${file2}">파일내려받기</a>
</body>

</html>

 

 

FileDownload.java(서블릿)

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:\\file_repo";
		String fileName = request.getParameter("fileName");
		System.out.println("fileName : " + fileName);
		OutputStream out = response.getOutputStream();
		
		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);
		while(true) {
			byte[] buffer = new byte[1024*8];
			int count = in.read(buffer);
			
			if(count == -1)
			{
				break;
				
			}
			out.write(buffer,0,count);
			
		}
		
		
		
	}

'프로그래밍 > JSP' 카테고리의 다른 글

Servlet&JSP - 사용자 데이터 전송 방식  (0) 2021.08.17
Servlet&JSP - tomcat  (0) 2021.08.17
jstl .jar파일 4개  (0) 2021.02.04
tomcat9 > console 한글깨짐 오류  (0) 2021.01.04
JSP 스크립트  (0) 2020.06.23
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유