0% found this document useful (0 votes)
139 views19 pages

HTML 5: JSP Servlet File Upload: INTE 30163: LECTURE 4

The document discusses file upload in Java web applications using servlets and JSP. It includes code for a FileLocationContextListener class that initializes a file directory, and an UploadDownloadFileServlet class that handles file uploads and downloads using Apache Commons FileUpload. It also includes code for an index.jsp page with a file upload form that submits to a upload.jsp page.

Uploaded by

Ethel Fajardo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views19 pages

HTML 5: JSP Servlet File Upload: INTE 30163: LECTURE 4

The document discusses file upload in Java web applications using servlets and JSP. It includes code for a FileLocationContextListener class that initializes a file directory, and an UploadDownloadFileServlet class that handles file uploads and downloads using Apache Commons FileUpload. It also includes code for an index.jsp page with a file upload form that submits to a upload.jsp page.

Uploaded by

Ethel Fajardo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

INTE 30163: LECTURE 4

HTML 5: JSP SERVLET FILE UPLOAD


FILE UPLOAD 1: USING SERVLET

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 {

public void contextInitialized(ServletContextEvent servletContextEvent) {


String rootPath = System.getProperty("catalina.home");
ServletContext ctx = servletContextEvent.getServletContext();
String relativePath = ctx.getInitParameter("tempfile.dir");
File file = new File(rootPath + File.separator + relativePath);
if(!file.exists()) file.mkdirs();
System.out.println("File Directory created to be used for storing files");
ctx.setAttribute("FILES_DIR_FILE", file);
ctx.setAttribute("FILES_DIR", rootPath + File.separator + relativePath);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
//do cleanup if needed
}
}

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");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}

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());

File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileItem.getName());


System.out.println("Absolute Path at server="+file.getAbsolutePath());
fileItem.write(file);
out.write("File "+fileItem.getName()+ " uploaded successfully.");
out.write("<br>");
out.write("<a href=\"UploadDownloadFileServlet?fileName="+fileItem.getName()+"\">Download "+fileItem.getName()+"</a>");
}
} catch (FileUploadException e) {
out.write("Exception in uploading file.");
} catch (Exception e) {
out.write("Exception in uploading file.");
}
out.write("</body></html>");
}

WEB CONTENT

index.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<jsp:include page="includes/header.html"></jsp:include>

<form action="UploadDownloadFileServlet" method="post" enctype="multipart/form-data">


<table class="table table-bordered" style="text-align: center;">
<tr>
<td><h3>Select File to Upload:</h3></td>
<td><input type="file" name="fileName"></td>
</tr>
<tr>
<td colspan=2><input type="submit" value="Upload"></td>
</tr>
</table>
</form>
<c:import url="/includes/footer.jsp" />
</body>
</html>

FILE UPLOAD 2: 2 JSP FILE

WEB CONTENT

ee_upload.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<jsp:include page="includes/header.html"></jsp:include>

<div class="jumbotron text-center" style="margin-bottom:0">


<h1>Employee Information Entry</h1>
</div>

<nav class="navbar navbar-expand-sm bg-success navbar-dark">


<a class="navbar-brand" href="#"><i class="jaedev ja-jaedevit_1"> </i> JAEDEV</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Employee</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Payslip</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Profile</a>
</li>
</ul>
</div>
</nav>

<div class="container" style="margin-top:30px">


<div class="col-12">
<form action="upload.jsp" method="post" enctype="multipart/form-data" name="eeForm" id="eeForm">
<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">
<c:if test="${message != null}">
<p><i>${message}</i></p>
</c:if>

<input type="hidden" name="action" value="add">

<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 class="col-md-4 mb-3">


<label class="control-label">E-Mail</label>
<div class="input-group">
<input type="text" name="email" class="form-control" required/>
<div class="input-group-append">
<span class="input-group-text">
<i class="fa fa-at"></i>
</span>
</div>
</div>
</div>

<div class="col-md-4 mb-3">


<label class="control-label">Image</label>
<div class="input-group">
<input type="file" name="image" class="custom-file-input" required/>
<label class="custom-file-label" for="customFile"> Choose file</label>

</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="col-md-4 mb-3">


<label class="control-label">Firstname</label>
<div class="input-group">
<input type="text" name="fname" 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="col-md-4 mb-3">
<label class="control-label">Middlename</label>
<div class="input-group">
<input type="text" name="mname" 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>

<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

<%@ page import="java.util.List" %>


<%@ page import="java.util.Iterator" %>
<%@ page import="java.io.File" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<jsp:include page="includes/header.html"></jsp:include>

<div class="jumbotron text-center" style="margin-bottom:0">


<h1>Employee Profile has been Uploaded</h1>
</div>
<%!
String todaydate="";
String email="";
String lname="";
String fname="";
String mname="";
String bday="";
String age="";
String bplace="";
String department="";
String position="";
String salary="";

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

<%@ page import="java.util.GregorianCalendar, java.util.Calendar" %>


<%
GregorianCalendar currentDate = new GregorianCalendar();
int currentYear = currentDate.get(Calendar.YEAR);
%>

<div class="footer fixed-bottom bg-success text-white">


<p>&copy; Copyright <%= currentYear %> JaedevIT by Ethel Fajardo</p>
</div>

<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;
}

var bmth = parseInt(d[1],10)-1; // radix 10!


if (bmth < 0 || bmth >11) { // check valid month 0-11
showMessage()
return false;
}
var bdy = parseInt(d[2],10); // radix 10!
var dim = daysInMonth(bmth+1,byr);
if (bdy <1 || bdy > dim) { // check valid date according to month
showMessage();
return false;
}

var age = nowyear - byr;


var nowmonth = today.getMonth();
var nowday = today.getDate();
if (bmth > nowmonth) {age = age - 1} // next birthday not yet reached
else if (bmth == nowmonth && nowday < bdy) {age = age - 1}

alert('You are ' + age + ' years old');


document.getElementById("age").value = age;
document.getElementById("age").focus();

if (age <= 15) {


alert ("You are 15 years old or less!");
document.getElementById("age").value = age;
document.getElementById("age").focus();
}
}

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();
}
}

function daysInMonth(month,year) { // months are 1-12


var dd = new Date(year, month, 0);
return dd.getDate();
}
</script>

</body>
</html>

You might also like