index.jsp
<form name="form" onSubmit='return validate();' action="change_photo.do" method="post" enctype="multipart/form-data">
<span style="padding-left: 30px">Upload Picture : <input type ="file" id="fileChooser" name="pic" style="margin-left: 23px"/></span><br /><br/>
<span class="submit" ><input type="submit" value="Change Photo" name="submit"/></span>
</form>
validation
<script type="text/javascript">
function validate()
{
var extensions = new Array("jpg","png");
var pic = document.form.pic.value;
var image_length = document.form.pic.value.length;
var pos = pic.lastIndexOf('.') + 1;
var ext = pic.substring(pos, image_length);
var final_ext = ext.toLowerCase();
for (i = 0; i < extensions.length; i++)
{
if(extensions[i] == final_ext)
{
if(val()){
return true;
}
}
}
alert("You must upload file with one of the following extensions: "+ extensions.join(', ') +".");
return false;
}
</script>
change_photo.java
package com;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.DbConnection;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadServlet
* @version 1.0
* @author www.codejava.net
*/
public class change_photo extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY = "upload";
private static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024; // 4MB
private static final int REQUEST_SIZE = 1024 * 1024 * 1; // 5MB
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
DbConnection dbc=new DbConnection();
Connection con=dbc.getCon();
Statement st=null;
ResultSet rs=null;
PreparedStatement pst=null;
String finalImg="";
String value="";
String value1="";
HttpSession hs=request.getSession();
String id=(String)hs.getAttribute("id");
st=con.createStatement();
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
// if not, we stop here
return;
}
// configures some settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(REQUEST_SIZE);
// constructs the directory path to store upload file
String uploadPath = getServletContext().getRealPath("")
+ File.separator + UPLOAD_DIRECTORY;
// creates the directory if it does not exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
System.out.print("file is there");
ArrayList<String> ll=new ArrayList<String>();
try
{
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
int s=formItems.size();
for(int i=0;i<1;i++)
{
Iterator iter = formItems.iterator();
// iterates over form's fields
while (iter.hasNext())
{
FileItem item = (FileItem) iter.next();
// processes only fields that are not form fields
if (!item.isFormField())
{
String fileName = item.getName();
Random gen = new Random();
int r = Math.abs(gen.nextInt());
String reg = "[.*]";
String replaceText = "";
String finalname=fileName;
System.out.print(finalname);
//System.out.println("Text before replacing is: " + fileName);
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(fileName);
StringBuffer buffer = new StringBuffer();
while(matcher.find())
{
matcher.appendReplacement(buffer, replaceText);
}
int indexOf = fileName.indexOf(".");
String domainName = fileName.substring(indexOf);
//System.out.println("Domain Name: "+ domainName);
//System.out.print(buffer.toString());
finalImg = buffer.toString()+r+i+domainName;
ll.add(finalImg);
System.out.println("Final Image: "+ finalImg);
String filePath = uploadPath + File.separator + finalImg;
File storeFile = new File(filePath);
//System.out.print(filePath);
// saves the file on disk
item.write(storeFile);
}
}
}
String sql="UPDATE `tbl_employee` SET `pic`=? WHERE id=?";
pst=con.prepareStatement(sql);
Iterator<String> iter=ll.iterator();
for(int i=1;iter.hasNext();i++)
{
String name=iter.next();
pst.setString(i,name);
}
pst.setString(2, id);
int i=pst.executeUpdate();
System.out.print("inserted" +i);
request.setAttribute("message", "Upload has been done successfully!");
}
catch (SQLException ex) {
request.setAttribute("message", "Something Went Wrong.");
}
} catch (Exception ex) {
request.setAttribute("message", "There was an error: Size Of photo must be less than (1 MB)");
}
getServletContext().getRequestDispatcher("/ChangePic.jsp").forward(request, response);
}
}
<form name="form" onSubmit='return validate();' action="change_photo.do" method="post" enctype="multipart/form-data">
<span style="padding-left: 30px">Upload Picture : <input type ="file" id="fileChooser" name="pic" style="margin-left: 23px"/></span><br /><br/>
<span class="submit" ><input type="submit" value="Change Photo" name="submit"/></span>
</form>
validation
<script type="text/javascript">
function validate()
{
var extensions = new Array("jpg","png");
var pic = document.form.pic.value;
var image_length = document.form.pic.value.length;
var pos = pic.lastIndexOf('.') + 1;
var ext = pic.substring(pos, image_length);
var final_ext = ext.toLowerCase();
for (i = 0; i < extensions.length; i++)
{
if(extensions[i] == final_ext)
{
if(val()){
return true;
}
}
}
alert("You must upload file with one of the following extensions: "+ extensions.join(', ') +".");
return false;
}
</script>
change_photo.java
package com;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.DbConnection;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadServlet
* @version 1.0
* @author www.codejava.net
*/
public class change_photo extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY = "upload";
private static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024; // 4MB
private static final int REQUEST_SIZE = 1024 * 1024 * 1; // 5MB
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
DbConnection dbc=new DbConnection();
Connection con=dbc.getCon();
Statement st=null;
ResultSet rs=null;
PreparedStatement pst=null;
String finalImg="";
String value="";
String value1="";
HttpSession hs=request.getSession();
String id=(String)hs.getAttribute("id");
st=con.createStatement();
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
// if not, we stop here
return;
}
// configures some settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(REQUEST_SIZE);
// constructs the directory path to store upload file
String uploadPath = getServletContext().getRealPath("")
+ File.separator + UPLOAD_DIRECTORY;
// creates the directory if it does not exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
System.out.print("file is there");
ArrayList<String> ll=new ArrayList<String>();
try
{
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
int s=formItems.size();
for(int i=0;i<1;i++)
{
Iterator iter = formItems.iterator();
// iterates over form's fields
while (iter.hasNext())
{
FileItem item = (FileItem) iter.next();
// processes only fields that are not form fields
if (!item.isFormField())
{
String fileName = item.getName();
Random gen = new Random();
int r = Math.abs(gen.nextInt());
String reg = "[.*]";
String replaceText = "";
String finalname=fileName;
System.out.print(finalname);
//System.out.println("Text before replacing is: " + fileName);
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(fileName);
StringBuffer buffer = new StringBuffer();
while(matcher.find())
{
matcher.appendReplacement(buffer, replaceText);
}
int indexOf = fileName.indexOf(".");
String domainName = fileName.substring(indexOf);
//System.out.println("Domain Name: "+ domainName);
//System.out.print(buffer.toString());
finalImg = buffer.toString()+r+i+domainName;
ll.add(finalImg);
System.out.println("Final Image: "+ finalImg);
String filePath = uploadPath + File.separator + finalImg;
File storeFile = new File(filePath);
//System.out.print(filePath);
// saves the file on disk
item.write(storeFile);
}
}
}
String sql="UPDATE `tbl_employee` SET `pic`=? WHERE id=?";
pst=con.prepareStatement(sql);
Iterator<String> iter=ll.iterator();
for(int i=1;iter.hasNext();i++)
{
String name=iter.next();
pst.setString(i,name);
}
pst.setString(2, id);
int i=pst.executeUpdate();
System.out.print("inserted" +i);
request.setAttribute("message", "Upload has been done successfully!");
}
catch (SQLException ex) {
request.setAttribute("message", "Something Went Wrong.");
}
} catch (Exception ex) {
request.setAttribute("message", "There was an error: Size Of photo must be less than (1 MB)");
}
getServletContext().getRequestDispatcher("/ChangePic.jsp").forward(request, response);
}
}