Il test risulta valido già dalla jdk 1.4.2
Ad esempio con Eclipse si crea un nuovo progetto web, si imposta il file xml secondo i parametri elencati qui sotto, si crea una form sulla index.jsp e infine si crea una nuova classe servlet.
web.xml e index.jsp
<?xml version="1.0" ?> <web-app> <display-name>nameproject</display-name> <servlet> <servlet-name>SaveFileUpload</servlet-name> <servlet-class>namePackage.SaveFileUpload</servlet-class> </servlet> <servlet-mapping> <servlet-name>SaveFileUpload</servlet-name> <url-pattern>/SaveFileUpload</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> <form method="post" name="form2" action="SaveFileUpload" enctype="multipart/form-data"> Select file:<input type="file" name="file_upload" /> <input class="submit1" name="btn_sub" value="Upload" type="submit" /> </form>
class SaveFileUpload
public class SaveFileUpload extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { saveFile(request, response, "GET"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { saveFile(request, response, "POST"); } public void saveFile(HttpServletRequest request, HttpServletResponse response, String methodGetPost) ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemsList=null; try { fileItemsList = servletFileUpload.parseRequest(request); } catch (FileUploadException e1) { errorServlet=true; e1.printStackTrace(); } FileItem fileItem = null; Iterator it = fileItemsList.iterator(); String fileName = ""; while (it.hasNext()){ fileItem = (FileItem)it.next(); if(fileItem.getFieldName().equals("file_upload")) { String pathFile=""; Init init = new Init(); pathFile = "c:\\"; //example pathFile = pathFile + request.getSession().getAttribute("user"); File dir = new File(pathFile); if (!dir.exists()) dir.mkdirs(); fileName = fileItem.getName(); if (fileItem.getSize() > 0){ fileName = FilenameUtils.getName(fileName); } File saveTo = new File(dir, fileName); try { fileItem.write(saveTo); }catch(Exception e){ e.printStackTrace(); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title></title>"); out.println("</head>"); out.println("<body>"); out.println("File salvato correttamente."); out.println("</form>"); out.println("</body>"); out.println("</html>"); } } } }