HTML 5: JSP Servlet File Upload: INTE 30163: LECTURE 4
HTML 5: JSP Servlet File Upload: INTE 30163: LECTURE 4
PACKAGE SERVLET
FileLocationContextListener.java
package servlet;
import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class FileLocationContextListener implements ServletContextListener {
UploadDownloadFileServlet.java
package servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/UploadDownloadFileServlet")
public class UploadDownloadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletFileUpload uploader = null;
@Override
public void init() throws ServletException{
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
fileFactory.setRepository(filesDir);
this.uploader = new ServletFileUpload(fileFactory);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
if(fileName == null || fileName.equals("")){
throw new ServletException("File Name can't be null or empty");
}
File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
if(!file.exists()){
throw new ServletException("File doesn't exists on server.");
}
System.out.println("File location on server::"+file.getAbsolutePath());
ServletContext ctx = getServletContext();
InputStream fis = new FileInputStream(file);
String mimeType = ctx.getMimeType(file.getAbsolutePath());
response.setContentType(mimeType != null? mimeType:"application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
ServletOutputStream os = response.getOutputStream();
byte[] bufferData = new byte[1024];
int read=0;
while((read = fis.read(bufferData))!= -1){
os.write(bufferData, 0, read);
}
os.flush();
os.close();
fis.close();
System.out.println("File downloaded at client successfully");
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head></head><body>");
try {
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
while(fileItemsIterator.hasNext()){
FileItem fileItem = fileItemsIterator.next();
System.out.println("FieldName="+fileItem.getFieldName());
System.out.println("FileName="+fileItem.getName());
System.out.println("ContentType="+fileItem.getContentType());
System.out.println("Size in bytes="+fileItem.getSize());
WEB CONTENT
index.jsp
<jsp:include page="includes/header.html"></jsp:include>
WEB CONTENT
ee_upload.jsp
<jsp:include page="includes/header.html"></jsp:include>
<div class="form-row">
<div class="col-md-4 mb-3">
<label class="control-label">Date</label>
<div class="input-group">
<input type="text" id="date" name="todaydate" class="form-control" readonly/>
<div class="input-group-append">
<span class="input-group-text">
<i class="fa fa-calendar-alt"></i>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<label class="control-label">Lastname</label>
<div class="input-group">
<input type="text" name="lname" class="form-control" required>
<div class="input-group-append">
<span class="input-group-text">
<i class="fas fa-id-card"></i>
</span>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<label class="control-label">Birthday</label>
<div class="input-group">
<input type="date" id="dob" name="bday" class="form-control" onblur="checkAge()" required>
<div class="input-group-append">
<span class="input-group-text">
<i class="far fa-calendar-day"></i>
</span>
</div>
</div>
</div>
<div class="col-md-4 mb-3">
<label class="control-label">Age</label>
<div class="input-group">
<input type="text" id="age" name="age" class="form-control" readonly>
<div class="input-group-append">
<span class="input-group-text">
<i class="far fa-calendar-plus"></i>
</span>
</div>
</div>
</div>
<div class="col-md-4 mb-3">
<label class="control-label">Birth Place</label>
<div class="input-group">
<input type="text" name="bplace" class="form-control" required>
<div class="input-group-append">
<span class="input-group-text">
<i class="far fa-map-marker-alt"></i>
</span>
</div>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<label class="control-label">Department</label>
<div class="input-group">
<input type="text" name="department" class="form-control" required>
<div class="input-group-append">
<span class="input-group-text">
<i class="far fa-building"></i>
</span>
</div>
</div>
</div>
<div class="col-md-4 mb-3">
<label class="control-label">Position</label>
<div class="input-group">
<input type="text" name="position" class="form-control" required>
<div class="input-group-append">
<span class="input-group-text">
<i class="fa fa-user-tie"></i>
</span>
</div>
</div>
</div>
<div class="col-md-4 mb-3">
<label class="control-label">Salary</label>
<div class="input-group">
<input type="text" name="salary" class="form-control" required>
<div class="input-group-append">
<span class="input-group-text">
<i class="fas fa-hand-holding-usd"></i>
</span>
</div>
</div>
</div>
</div>
</div>
<div class="card-footer" style="text-align: right;">
<button class="btn btn-rounded btn-primary" onclick="return confirm('Are you sure you want to SAVE this record?');"
type="submit"><i class="fa fa-save"></i> Save</button>
<button class="btn btn-rounded btn-danger" onclick="return confirm('Are you sure you want to Clear this record?');"
type="reset"><i class="fas fa-undo"></i> Reset</button>
</div>
</div>
</form>
</div>
<c:import url="/includes/footer.jsp" />
</div>
upload.jsp
<jsp:include page="includes/header.html"></jsp:include>
int count1=0,count2=0,count3=0,count4=0,count5=0,count6=0,count7=0,count8=0,count9=0,count10=0,count11=0;
%>
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {}
else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
}
catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
if(name.equals("todaydate")) {
todaydate=value;
count1=1;
}
if(name.equals("email")) {
email=value;
count2=2;
}
if(name.equals("lname")) {
lname=value;
count3=3;
}
if(name.equals("fname")) {
fname=value;
count4=4;
}
if(name.equals("mname")) {
count5=5;
mname=value;
}
if(name.equals("bday")) {
count6=6;
bday=value;
}
if(name.equals("age")) {
count7=7;
age=value;
}
if(name.equals("bplace")) {
count8=8;
bplace=value;
}
if(name.equals("department")) {
count9=9;
department=value;
}
if(name.equals("position")) {
count10=10;
position=value;
}
if(name.equals("salary")) {
count11=11;
salary=value;
}
}
else{
try {
String itemName = item.getName();
File savedFile = new File(config.getServletContext().getRealPath("/")+"uploads\\"+itemName);
item.write(savedFile);
%>
<div class="container" style="margin-top:30px">
<div class="col-10">
<div class="card">
<div class="card-header bg-inverse">
<i class="fas fa-edit"></i>
<a class="card-title"> EMPLOYEE INFORMATION</a>
</div>
<div class="card-body">
<div class="form-row">
<div class="col-md-4 mb-3">
<div class="input-group">
<img class="img-thumbnail" src=uploads/<%=itemName%> alt="image">
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<div class="input-group">
<table class="table table-bordered table-hover" style="text-align: center;">
<%
if(count1==1)
out.println("<tr><td><b>Date</td><td><b>"+todaydate);
if(count2==2)
out.println("</td><tr><td><b>E-
Mail</td><td><b>"+email);
if(count3==3)
out.println("</td><tr><td
><b>Lastname</td><td><b>"+lname);
if(count4==4)
out.println("</td><tr><td
><b>Firstname</td><td><b>"+fname);
if(count5==5)
out.println("</td><tr><td
><b>Middlename</td><td><b>"+mname);
if(count5==5)
out.println("</td><tr><td
><b>Birthday</td><td><b>"+bday);
if(count5==5)
out.println("</td><tr><td ><b>Age</td><td><b>"+age);
if(count5==5)
out.println("</td><tr><td ><b>Birth
Place</td><td><b>"+bplace);
if(count5==5)
out.println("</td><tr><td
><b>Department</td><td><b>"+department);
if(count5==5)
out.println("</td><tr><td
><b>Position</td><td><b>"+position);
if(count5==5)
out.println("</td><tr><td
><b>Salary</td><td><b>"+salary);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
%>
</table>
</div>
</div>
</div>
</div>
<div class="card-footer" style="text-align: right;">
<form action="" method="post">
<button class="btn btn-rounded btn-info" onclick="return confirm('Are you sure you want to ENTER
another record?');" type="submit"><i class="fa fa-undo"></i> Back</button>
</form>
</div>
</div>
</div>
</div>
INCLUDES FOLDER
header.html
<!DOCTYPE html>
<html>
<head>
<title>Employee Record</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--ICON -->
<link href="img/favicon.png" rel="icon" type="image/png" sizes="16x16">
<!--CSS -->
<link href="css/bootstrap.css" rel="stylesheet"/>
<link href="font/css/all.css" rel="stylesheet"/>
<link href="jaedevit/style.css" rel="stylesheet">
</head>
<body>
footer.jsp
<script>
date = new Date();
var month = date.getMonth()+1;
var day = date.getDate();
var year = date.getFullYear();
document.getElementById("date").value = month + '/' + day + '/' + year;
</script>
<script>
function checkAge(){
var today = new Date();
var d = document.getElementById("dob").value;
if (!/\d{4}\-\d{2}\-\d{2}/.test(d)) { // check valid format
showMessage();
return false;
}
d = d.split("-");
var byr = parseInt(d[0]);
var nowyear = today.getFullYear();
if (byr >= nowyear || byr < 1900) { // check valid year
showMessage();
return false;
}
function showMessage() {
if (document.getElementById("dob").value != "") {
alert ("Invalid date format or impossible year/month/day of birth - please re-enter as nowyearYY-MM-DD");
document.getElementById("dob").value = "";
document.getElementById("dob").focus();
}
}
</body>
</html>