Tuesday 30 September 2014

Image Upload Using servlet /Store image in data base

Image (Photo) Upload Using Java Servlet and JSP


Please Download below jar File:


  • commons-fileupload-1.2.2.jar
  • commons-io-2.5-20121102.152256-3.jar



Java Class: UploadFile .class

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFile extends HttpServlet {

private static final String upload="upload";
private static final int thread =1024*1024*3;
private static final int filesize=1024*1024*40;
private static final int reqsize=1024*1024*50;

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


if(!ServletFileUpload.isMultipartContent(req)){
System.out.println(" please select file ");
}
else{
DiskFileItemFactory factory= new DiskFileItemFactory();
factory.setSizeThreshold(thread);
factory.setRepository(new File(System.getProperty("java.io.temdir")));

ServletFileUpload fileUpload= new ServletFileUpload(factory);
fileUpload.setSizeMax(reqsize);
fileUpload.setFileSizeMax(filesize);

String path=getServletContext().getRealPath("")+File.separator+upload;


File file= new File(path);

if(!file.exists()){
file.mkdir();
}
try{
List list=fileUpload.parseRequest(req);
Iterator  iter=list.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 = new File(item.getName()).getName();
String filePath =upload+File.separator+fileName;
File storeFile = new File(filePath);

// saves the file on disk
item.write(storeFile);
}
}

}
catch (Exception e) {
// TODO: handle exception
}


}
}
}



JSP Page: index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>




Insert title here




select File :








web.xml



  UploadFile

 
  index.jsp
 
 
 
  uplaod
  Uploadfile
 
 
 
  uplaod
  /upload