Why is this simple file upload not working? JSF
- by Nitesh Panchal
Hello,
Why is this code not working? I always get size() = 0, whenever i upload file.
xhtml file :-
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Abc</title>
</h:head>
<h:body>
<center>
<form method="post" enctype="multipart/form-data" id="form" action="/upload/uploadFile">
<input type="file"/> <br/>
<input type="Submit" value="upload"/>
</form>
</center>
</h:body>
</html>
This is my servlet :-
package servlets;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
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(name="uploadFile", urlPatterns={"/uploadFile"})
public class uploadFile extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, FileUploadException {
System.out.println("executed!");
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
System.out.println(items.size());
for (FileItem item : items) {
if (!item.isFormField()) {
System.out.println("Name: " + item.getName());
System.out.println("Size: " + item.getSize());
System.out.println("Type: " + item.getContentType());
}
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (FileUploadException ex) {
ex.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (FileUploadException ex) {
ex.printStackTrace();
}
}
@Override
public String getServletInfo() {
return "Short description";
}
}