Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Commands; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.servlet.http.HttpServlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * * @author USER */ public class readFileCommand extends HttpServlet implements Command { @Override public String executeCommand(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String UPLOAD_DIRECTORY = "C:\\Users\\USER\\Downloads\\Movies"; String forwardToJsp = ""; HttpSession session = request.getSession(true); if (ServletFileUpload.isMultipartContent(request)) { try { ArrayList<FileItem> multiparts = (ArrayList<FileItem>) new ServletFileUpload( new DiskFileItemFactory()).parseRequest(request); FileItem item = multiparts.get(0); if (!item.getName().isEmpty()) { String name = new File(item.getName()).getName(); String filename = UPLOAD_DIRECTORY + File.separator + name; File f = new File(filename); boolean exists = f.exists(); //if (!exists) { if (!item.isFormField()) { item.write(f); // if (fm.readFile(f)) { // forwardToJsp = "Movie.jsp"; // session.setAttribute("filename", filename); // session.setAttribute("allGenre", fm.allGenre()); // session.setAttribute("allMovie", fm.allMovie()); // session.setAttribute("most", fm.displayMost()); // session.setAttribute("score", fm.scoreInGroup()); // session.setAttribute("avgScore", fm.displayAverage()); // session.setAttribute("scoreOrder", fm.scoreOrder()); // } else { // session.setAttribute("message", "fail to read file"); // } } // } else { // session.setAttribute("message", "File already exists"); // forwardToJsp = "index.jsp"; //} } else { session.setAttribute("message", "No File Choosen"); } } catch (Exception ex) { session.setAttribute("message", ex.getMessage() + ex.getClass()); } } else { session.setAttribute("message", "Sorry this Servlet only handles file upload request"); } return forwardToJsp; } }