_Csandeep

Apache Commons File Upload Example

May 14th, 2013 (edited)
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.15 KB | None | 0 0
  1. /*
  2.  *   REFERENCE:
  3.  *   http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet/2424824#2424824
  4.  *
  5.  */
  6.  
  7. List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
  8.  
  9. for (FileItem item : items) {
  10.      
  11.      if (item.isFormField()) {
  12.                    
  13.                
  14.      }else{ // Process the form file field (input type="file")
  15.                    
  16.     String fileName = FilenameUtils.getName(item.getName());
  17.                    
  18.     System.out.println("Filename -> " + fileName);
  19.                    
  20.     String realPath = getServletContext().getRealPath("/");
  21.                    
  22.     File file = new File(realPath+"/uploadFolder");
  23.        
  24.     file.mkdir();
  25.                    
  26.     String prefix = FilenameUtils.getBaseName(fileName) + "_";
  27.                    
  28.     String suffix = "." + FilenameUtils.getExtension(fileName);
  29.                    
  30.     // Prepare filename prefix and suffix for an unique filename in upload folder.
  31.                    
  32.     File tempFile = File.createTempFile(prefix, suffix,file);  
  33.                    
  34.     System.out.println("tempFile -> "+tempFile);
  35.                    
  36.     item.write(tempFile); // File uploaded to "uploadFolder" in Web Server(Not database)
  37.                    
  38.     // Save the File path(String) to Database now.
  39.                    
  40.    }
  41. }
Add Comment
Please, Sign In to add comment