I am trying to run a servlet fileupload example in tomcat 7 which is based on org.apache.commons.fileupload
i complied servlet class file in CMD (Win 7 64bit) by using this command.
C:\Users\Preet\Desktop>javac -cp .;E:/servlet-api.jar;"C:\Program Files\Apache S
oftware Foundation\Tomcat 7.0\webapps\sim\WEB-INF\lib\commons-fileupload-1.2.2.j
ar" "C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\sim\WEB-INF\
classes\SimpleServlets.java"
Everything was fine.
After compiling i tried my example i got a error which is
exception
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest
org.apache.commons.fileupload.servlet.ServletFileUpload.isMultipartContent(ServletFileUpload.java:68)
SimpleServlets.doPost(SimpleServlets.java:21)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
then at last googling, found few solution and i followed them one by one.
1.Made a lib folder in WEB-INF and copied commons-fileupload-1.2.2 and commons-io-2.2. But no luck.
2.Copied commons-fileupload-1.2.2 and commons-io-2.2 in tomcat/lib. But no luck.
3.Add commons-fileupload-1.2.2 and commons-io-2.2 to classpaath but no luck.
Please tell me what is wrong.
My code
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.File;
import java.util.List;
import java.util.Iterator;
public class SimpleServlets extends HttpServlet {
private static final long serialVersionUID = -3208409086358916855L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}