<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="fileForm" method="POST" enctype="multipart/form-data" action="fileupload01_process.jsp">
<p> 이름 : <input type="text" name="name"> </p>
<p> 제목 : <input type="text" name="subject"> </p>
<p> 파일 : <input type="file" name="filename"> </p>
<p> <input type="submit" value="파일 올리기"> </p>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.oreilly.servlet.*" %>
<%@ page import="com.oreilly.servlet.multipart.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
MultipartRequest multi = new MultipartRequest(request, "C:\\upload", 5*1024*1024, "UTF-8", new DefaultFileRenamePolicy());
Enumeration params = multi.getParameterNames();
while(params.hasMoreElements()) {
String name = (String) params.nextElement();
String value = multi.getParameter(name);
out.println(name + " = "+ value + "<br>");
}
out.println("-------------------------------<br>");
Enumeration files = multi.getFileNames();
while(files.hasMoreElements()) {
String name = (String) files.nextElement();
String filename = multi.getFilesystemName(name);
String original = multi.getOriginalFileName(name);
String type = multi.getContentType(name);
File file = multi.getFile(name);
out.println("요청 파라미터 이름 : "+name+"<br>");
out.println("실제 파일 이름 : "+original+"<br>");
out.println("저장 파일 이름 : "+filename+"<br>");
out.println("파일 콘텐츠 유형 : "+type+"<br>");
if(file != null) {
out.println("파일 크기 : "+ file.length());
out.println("<br>");
}
}
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="fileForm" method="post" enctype="multipart/form-data" action="fileupload02_process.jsp">
<p>
이름1 : <input type="text" name="name1">
제목1 : <input type="text" name="subject1">
파일1 : <input type="file" name="filename1">
</p>
<p>
이름2 : <input type="text" name="name2">
제목2 : <input type="text" name="subject2">
파일2 : <input type="file" name="filename2">
</p>
<p>
이름3 : <input type="text" name="name3">
제목3 : <input type="text" name="subject3">
파일3 : <input type="file" name="filename3">
</p>
<p><input type="submit" value="파일 올리기"></p>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.oreilly.servlet.*" %>
<%@ page import="com.oreilly.servlet.multipart.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
MultipartRequest multi = new MultipartRequest(request, "C:\\upload", 5*1024*1024, "utf-8", new DefaultFileRenamePolicy());
String name1 = multi.getParameter("name1");
String subject1 = multi.getParameter("subject1");
String name2 = multi.getParameter("name2");
String subject2 = multi.getParameter("subject2");
String name3 = multi.getParameter("name3");
String subject3 = multi.getParameter("subject3");
Enumeration files = multi.getFileNames();
String file3 = (String)files.nextElement();
String filename3 = multi.getFilesystemName(file3);
String file2 = (String)files.nextElement();
String filename2 = multi.getFilesystemName(file2);
String file1 = (String)files.nextElement();
String filename1 = multi.getFilesystemName(file1);
%>
<table border="1">
<tr>
<th width="100">이름</th>
<th width="100">제목</th>
<th width="100">파일</th>
</tr>
<%
out.print("<tr><td>"+name1+"</td>");
out.print("<td>"+subject1+"</td>");
out.print("<td>"+filename1+"</td></tr>\n");
out.print("<tr><td>"+name2+"</td>");
out.print("<td>"+subject2+"</td>");
out.print("<td>"+filename2+"</td></tr>\n");
out.print("<tr><td>"+name3+"</td>");
out.print("<td>"+subject3+"</td>");
out.print("<td>"+filename3+"</td></tr>\n");
%>
</table>
</body>
</html>
파일 업로드 패키지
서버의 메모리상에서 파일 처리가 가능하도록 지원
오픈 라이브러리 commons-fileupload.jar, commons-io.jar 파일을 배포 사이트에서 직접 다운로드해서 사용
JSP 페이지에 page 디렉티브 태그의 import 속성을 사용하여 패키지 org.apache.commons.fileupload.*를 설정
DiskFileUpload 클래스의 메소드
FileItem 클래스의 메소드
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="fileupload03_process.jsp" method="post" enctype="multipart/form-data">
<p> 파일 : <input type="file" name="filename"></p>
<p> <input type="submit" value="파일 올리기"></p>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String fileUploadPath = "C:\\upload";
DiskFileUpload upload = new DiskFileUpload();
List item = upload.parseRequest(request);
Iterator params = item.iterator();
while(params.hasNext()) {
FileItem fileItem = (FileItem)params.next();
if(!fileItem.isFormField()) {
String fileName = fileItem.getName();
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
File file = new File(fileUploadPath + "/"+fileName);
fileItem.write(file);
}
}
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="fileupload04_process.jsp" method="post"
enctype="multipart/form-data">
<p>
이름 : <input type="text" name="name">
</p>
<p>
제목 : <input type="text" name="subject">
</p>
<p>
파일 : <input type="file" name="filename">
</p>
<p>
<input type="submit" value="파일 올리기">
</p>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String path = "C:\\upload";
DiskFileUpload upload = new DiskFileUpload();
upload.setSizeMax(1000000);
upload.setSizeThreshold(4096);
upload.setRepositoryPath(path);
List items = upload.parseRequest(request);
Iterator params = items.iterator();
while(params.hasNext()) {
FileItem item = (FileItem)params.next();
if(item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("utf-8");
out.println(name+"="+value+"<br>");
} else {
String fileFieldName= item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
fileName = fileFieldName.substring(fileName.lastIndexOf("\\")+1);
long fileSize = item.getSize();
File file = new File(path+"/"+fileName);
item.write(file);
out.println("----------------------------<br>");
out.println("요청 파라미터 이름 : "+fileFieldName+"<br>");
out.println("저장 파일 이름 : "+fileName+"<br>");
out.println("파일 콘텐츠 유형 : "+contentType+"<br>");
out.println("파일 크기 : "+fileSize);
}
}
%>
</body>
</html>
package dto;
import java.io.Serializable;
public class Product implements Serializable{
private static final long serialVersionUID = 1L;
private String productId; // 상품아이디
private String pname; // 상품명
private Integer unitPrice; // 상품가격
private String description; // 상품설명
private String manufacturer; // 제조사
private String category; // 분류
private long unitInStock; // 재고수
private String condition; // 신상품 or 중고품 or 재생품
private String filename; // 이미지 파일명
public Product() {
super();
}
public Product(String productId, String pname, Integer unitPrice){
this.productId = productId;
this.pname = pname;
this.unitPrice = unitPrice;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Integer getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(Integer unitPrice) {
this.unitPrice = unitPrice;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public long getUnitInStock() {
return unitInStock;
}
public void setUnitInStock(long unitInStock) {
this.unitInStock = unitInStock;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public static long getSerialcersionuid() {
return serialVersionUID;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
package dao;
import java.util.ArrayList;
import dto.Product;
public class ProductRepository {
private ArrayList<Product> listOfProducts = new ArrayList<Product>();
private static ProductRepository instance = new ProductRepository();
public static ProductRepository getInstance() {
return instance;
}
public ProductRepository() {
Product phone = new Product("P1234", "iPhone 6s", 800000);
phone.setDescription("4.7-inch, 1334X750 Renina HD display, 8-megapixel iSight Camera");
phone.setCategory("Smart Phone");
phone.setManufacturer("Apple");
phone.setUnitInStock(1000);
phone.setCondition("New");
phone.setFilename("p1234.PNG");
Product notebook = new Product("P1235", "LG PC 그램", 1500000);
notebook.setDescription("13.3-inch, IPS LED display, 5rd Generation notebook. Inter Core processors");
notebook.setCategory("Notebook");
notebook.setManufacturer("LG");
notebook.setUnitInStock(1000);
notebook.setCondition("Refurbished");
notebook.setFilename("p1235.PNG");
Product tablet = new Product("P1236", "Galaxy Tab S", 900000);
tablet.setDescription("212.8*125.6*6.6mm, Super AMOLEED display, Octa-Core processor");
tablet.setCategory("Tablet");
tablet.setManufacturer("Samsum");
tablet.setUnitInStock(1000);
tablet.setCondition("Old");
tablet.setFilename("p1236.PNG");
listOfProducts.add(phone);
listOfProducts.add(notebook);
listOfProducts.add(tablet);
}
public ArrayList<Product> getAllProducts() {
return listOfProducts;
}
public Product getProductById(String productId) {
Product productById = null;
for (int i = 0; i < listOfProducts.size(); i++) {
Product product = listOfProducts.get(i);
if(product != null && product.getProductId() != null && product.getProductId().equals(productId)){
productById = product;
break;
}
}
return productById;
}
public void addProduct(Product product) {
listOfProducts.add(product);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="dto.Product"%>
<%@ page import="dao.ProductRepository" %>
<jsp:useBean id="productDAO" class="dao.ProductRepository"
scope="session" />
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>상품 목록</title>
<style>
.main .content .row {
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap : wrap;
}
.main .content .row .column {
width: 300px;
display: flex;
flex-direction: column;
justify-content: center;
margin: 15px 0;
}
.main .content .row .column h3, .main .content .row .column p {
text-align: center;
padding: 10px;
}
.main .content .row .column h3 {
font-size: 1.7rem;
font-weight: 400;
}
</style>
<%!String greenting = "상품목록";%>
</head>
<body>
<jsp:include page="header.jsp" />
<div class="main">
<div class="banner">
<div class="container">
<h1><%=greenting%></h1>
</div>
</div>
<div class="content">
<%
ProductRepository dao = ProductRepository.getInstance();
ArrayList<Product>listOfProducts = dao.getAllProducts();
%>
<div class="container">
<div class="row">
<%
for (int i = 0; i < listOfProducts.size(); i++) {
Product product = listOfProducts.get(i);
%>
<div class="column">
<img src="c:/upload/<%=product.getFilename()%>" alt="상품사진" style="width:100%">
<h3><%=product.getPname()%></h3>
<p><%=product.getDescription()%></p>
<p><%=product.getUnitPrice()%>원
</p>
<p>
<a href="./product.jsp?id=<%=product.getProductId()%>"
class="btn" role="button">상세 정보»</a>
</div>
<%
}
%>
</div>
<hr>
</div>
</div>
</div>
<jsp:include page="footer.jsp" />
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="dto.Product"%>
<%@ page import="dao.ProductRepository"%>
<jsp:useBean id="productDAO" class="dao.ProductRepository"
scope="session" />
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>상품 상세 정보</title>
<style>
.content .row {
padding: 30px 0;
display : flex;
}
.content .row div {
padding : 10px;
}
.content h3, .content p, .content h4 {
margin: 25px 0;
}
.content h3 {
margin-bottom: 5px;
}
.content .description {
margin-top: 5px;
}
.content .badge {
background-color: #f00;
color: #fff;
border-radius: 5px;
}
</style>
</head>
<body>
<jsp:include page="header.jsp" />
<div class="main">
<div class="banner">
<div class="container">
<h1>상품 정보</h1>
</div>
</div>
<%
String id = request.getParameter("id");
ProductRepository dao = ProductRepository.getInstance();
Product product = dao.getProductById(id);
%>
<div class="content">
<div class="container">
<div class="row">
<div>
<img alt="상품 사진" style="width:100%"
src="c:/upload/<%=product.getFilename()%>">
</div>
<div>
<h3><%=product.getPname()%></h3>
<p class="description"><%=product.getDescription()%></p>
<p>
<b>상품 코드 : </b><span class="badge"><%=product.getProductId()%></span>
<p>
<b>제조사</b> :
<%=product.getManufacturer()%></p>
<p>
<b>분류</b> :
<%=product.getCategory()%></p>
<p>
<b>재고 수</b> :
<%=product.getUnitInStock()%>
</p>
<h4><%=product.getUnitPrice()%>원
</h4>
<p>
<a href="#" class="btn btn-secondary">상품 주문 »</a> <a
href="./products.jsp" class="btn">상품 목록 »</a>
</p>
</div>
</div>
<hr>
</div>
</div>
</div>
<jsp:include page="footer.jsp" />
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>상품 등록</title>
<style>
.inputRow {
margin: 15px 0px;
display: flex;
align-items : center;
}
.inputRow label {
width : 150px;
}
.inputRow input, .inputRow textarea {
font-size: 1.3rem;
}
.inputRow input.btn {
font-size: 1rem;
padding : 5px 15px;
}
</style>
</head>
<body>
<jsp:include page="header.jsp" />
<div class="main">
<div class="banner">
<div class="container">
<h1>상품 등록</h1>
</div>
</div>
<div class="content">
<div class="container">
<form name="newProduct" action="./processAddProduct.jsp"
class="form-horizontal" method="post" enctype="multipart/form-data">
<div class="inputRow">
<label for="productId">상품 코드</label> <input type="text"
name="productId" id="productId">
</div>
<div class="inputRow">
<label for="name">상품 명</label> <input type="text" name="name" id ="name">
</div>
<div class="inputRow">
<label for="unitPrice">가격</label> <input type="text" name="unitPrice" id="unitPrice">
</div>
<div class="inputRow">
<label for="description">상세 정보</label>
<textarea name="description" cols="50" rows="2" id="description">
</textarea>
</div>
<div class="inputRow">
<label for="manufacturer">제조사</label> <input type="text" name="manufacturer" id="manufacturer">
</div>
<div class="inputRow">
<label for="category">분류</label> <input type="text" name="category" id="category">
</div>
<div class="inputRow">
<label for="unitStock">재고 수</label> <input type="text" name="unitInStock" id="unitStock">
</div>
<div class="inputRow">
<label>상태</label>
<label><input type="radio" name="condition" value="New"> 신규 제품</label>
<label><input type="radio" name="condition" value="Old"> 중고 제품</label>
<label><input type="radio" name="condition" value="Refurbished"> 재생 제품</label>
</div>
<div class="inputRow">
<label for="productImage">이미지</label>
<input type="file" name="productImage" id="productImage">
</div>
<div class="inputRow">
<input type="submit" value="등록" class="btn btn-secondary">
</div>
</form>
<hr>
</div>
</div>
</div>
<jsp:include page="footer.jsp" />
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.oreilly.servlet.*" %>
<%@ page import="com.oreilly.servlet.multipart.*" %>
<%@ page import="java.util.*" %>
<%@ page import="dto.Product" %>
<%@ page import="dao.ProductRepository" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
String filename = "";
String realFolder = "C:\\upload"; // 웹 애플리케이션상의 절대 경로
int maxSize = 5*1024*1024; // 최대 업로드될 파일의 크기 5MB
String encType = "utf-8"; // 인코딩 유형
MultipartRequest multi = new MultipartRequest(request, realFolder, maxSize, encType, new DefaultFileRenamePolicy());
String productId = multi.getParameter("productId");
String name = multi.getParameter("name");
String unitPrice = multi.getParameter("unitPrice");
String description = multi.getParameter("description");
String manufacturer = multi.getParameter("manufacturer");
String category = multi.getParameter("category");
String unitInStock = multi.getParameter("unitInStock");
String condition = multi.getParameter("condition");
Integer price;
if(unitPrice.isEmpty())
price = 0;
else
price = Integer.parseInt(unitPrice);
long stock;
if(unitInStock.isEmpty())
stock = 0;
else
stock = Long.parseLong(unitInStock);
Enumeration files = multi.getFileNames();
String fname = (String)files.nextElement();
String fileName = multi.getFilesystemName(fname);
ProductRepository dao = ProductRepository.getInstance();
Product newProduct = new Product();
newProduct.setProductId(productId);
newProduct.setPname(name);
newProduct.setUnitPrice(price);
newProduct.setDescription(description);
newProduct.setManufacturer(manufacturer);
newProduct.setCategory(category);
newProduct.setUnitInStock(stock);
newProduct.setCondition(condition);
newProduct.setFilename(fileName);
dao.addProduct(newProduct);
response.sendRedirect("products.jsp");
%>
</body>
</html>
교재에 삽입된 일러스트나 표 같은 소스는 어디서 구하시나요?