반응형
JSP 첨부파일 업로드 하기 쉬운 예제
서버에 첨부파일 업로드하는 간단한 예제를 만들어 봤습니다.
준비물
apache 에서 제공하는 Liblibrary 필요
보통 왠만한 was 구성시에는 기본으로 들어가는 애들이긴 합니다.
아래 maven 레파지토리에서 버전 확인후 다운 가능.
1. commons-fileupload
mvnrepository.com/artifact/commons-fileupload/commons-fileupload
2. commons-io
mvnrepository.com/artifact/commons-io/commons-io
아래 1,2 번 파일을 동일 위치에 넣고, upload.html 페이지에서 첨부 하면 됨.
1. 파일 전송 페이지 - upload.html
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "./upload.jsp" method = "post"
enctype = "multipart/form-data">
<input type = "file" name = "file" size = "50" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</body>
</html>
2. 첨부파일 받는 역할 - upload.jsp
java servlet으로 만들어도 되고, 아래처럼 그냥 jsp 형태로 써도 된다.
<%@ page import = "java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import = "javax.servlet.http.*" %>
<%@ page import = "org.apache.commons.fileupload.*" %>
<%@ page import = "org.apache.commons.fileupload.disk.*" %>
<%@ page import = "org.apache.commons.fileupload.servlet.*" %>
<%@ page import = "org.apache.commons.io.output.*" %>
<%
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>JSP File upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () ) {
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () ) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ) {
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
} else {
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + filePath +
fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
} catch(Exception ex) {
System.out.println(ex);
}
} else {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
}
%>
'프로그래밍 > JAVA' 카테고리의 다른 글
자바 String 원하는 문자열 추출 (indexOf, subString, chatAt, token, parseInt ) (0) | 2021.07.06 |
---|---|
디자인 패턴 Builder Pattern (0) | 2021.02.24 |
JAVA object equals, String equals 는 뭐가 다를까? (5) | 2021.02.19 |
java 디자인 패턴 Decorator 패턴 (0) | 2021.02.17 |
JAVA SHA 256 암호화 예제소스 (0) | 2021.02.15 |
댓글