Loading
File Upload Servlet DiskFileItemFactory ServletFileUpload

Java Quick Notes

Refresh Your Java - Before Java Interview

We are Agile, believe in less Documentation - Only Quick notes (Java Interview Questions) of Java/J2ee Read more....


Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

Go to SiteMap

Q)  File Upload Servlet by using "DiskFileItemFactory", "ServletFileUpload"


Ans)

FileUploadServlet:
Uploads any Kind of file using Java.

This Example shows us how to upload a File (.cvs or .rtf) by using
Apache fileupload API such as "DiskFileItemFactory", "ServletFileUpload".

In this Example we are uploading a .cvs file which holds the Customer
Data such as "Customer FirstName"  Or  "Customer LastName". This Java
classes reads the uploaded file and creates "CustomerVO" (Customer Value Object)
list.

In the same manner based on "fileName.endsWith(".csv")" please write logic for RTF.


import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import com.Ostermiller.util.ExcelCSVParser;
import com.Ostermiller.util.LabeledCSVParser;


public class FileUploadServlet extends HttpServlet {
    @Override
      protected void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws ServletException, IOException {
          super.doGet(req, resp);
      }
 
      @Override
      protected void doPost(HttpServletRequest req, HttpServletResponse resp)
              throws ServletException, IOException {
        
       String uploadType = req.getParameter(UPLOAD_TYPE);
       if(uploadType != null && uploadType.equalsIgnoreCase("uploadCustomer")){
        uploadCusterDetails(req, resp);
       }
       else{
        uploadSomeOtherData(req, resp);
       }
      }
    
    
      private void uploadCustomerData(HttpServletRequest req,
   HttpServletResponse resp) throws ServletException, IOException {
     
    //get the PrintWriter object to write the html page
       PrintWriter writer = resp.getWriter();
     
       // Check that we have a file upload request
       boolean isMultipart = ServletFileUpload.isMultipartContent(req);
       Map <String, String>  customerManagment = new Hashtable <String, String>();
 
       // process only multipart requests
       if (isMultipart) {
 
           // Create a factory for disk-based file items
           FileItemFactory factory = new DiskFileItemFactory();
 
           // Create a new file upload handler
           ServletFileUpload upload = new ServletFileUpload(factory);
         ArrayList<CustomerVO> CustomerVOList = new ArrayList<CustomerVO>();
         
          try {
               List<FileItem> items = upload.parseRequest(req);
               boolean errorReceived = false;
             
               for (FileItem item : items) {
                   if (item.isFormField()) continue;
                 
                   String fileName = item.getName();
                   // get only the file name not whole path
                   if (fileName != null) {
                        fileName = FilenameUtils.getName(fileName);
                   }
                
                   if(fileName.endsWith(".csv")) {
                    LabeledCSVParser labeledCsvParser = new LabeledCSVParser(
     new ExcelCSVParser(item.getInputStream()));
                    int lineCount = 0;
                       int lineNum = 0;
                       String [] testLabels = labeledCsvParser.getLabels();
                       List <String> list = Arrays.asList(testLabels);
                       if(list.size() < 3){
                        writer.print("File Not Valid");
                           resp.flushBuffer();
                           errorReceived =true;
                           break;
                         
                       }else if(!(list.contains(CUST_FIRST_COLUMN)&& list.contains(
        CUST_FIRST_COLUMN) && list.contains(CUSTOMER_EMAIL)))
        {
                           writer.print("File Not Valid");
                           resp.flushBuffer();
                           errorReceived =true;
                           break;
                       }
                       while (labeledCsvParser.getLine() != null) {
                           ++lineCount;
                         
                          CustomerVO customerVO = new CustomerVO();
                          String customerFirstName = labeledCsvParser.getValueByLabel(
           STARTING_CUST_FIRST_COLUMN);
                        
                          if(!"".equals(customerFirstName) && customerFirstName != null){
                           if(customerFirstName.length() > 10){
                            customerFirstName = customerFirstName.substring(0, 10);
                           }
                           if(customerManagment.containsValue(customerFirstName.trim())){
                                continue;
                               }
                           customerVO.setCustomerFirstName(customerFirstName.trim());
                           customerManagment.put(customerFirstName.trim(),
                  customerFirstName.trim());
                          }
                       
                          String customerLastName = labeledCsvParser.getValueByLabel(
             ENDING_CUST_FIRST_COLUMN);
                          if(!"".equals(customerLastName) && customerLastName != null){
                           if(customerLastName.length() > 10){
                            customerLastName = customerLastName.substring(0, 10);
                           }
                            if(customerManagment.containsValue(customerLastName.trim())){
                             continue;
                             }
                            CustomerVO.setLastName(customerLastName.trim());
                            customerManagment.put(customerLastName.trim(), customerLastName.trim());
                          }
                       
                          String currentProvider = labeledCsvParser.getValueByLabel(CUSTOMER_EMAIL);
                          if(!"".equals(currentProvider) && currentProvider != null){
                           if(currentProvider.length() > 255){
                            currentProvider = currentProvider.substring(0, 255);
                           }
                           CustomerVO.setCurrentProvider(currentProvider.trim());
                          }
                        
                          if ("".equals(customerFirstName.trim()) && "".equals(customerLastName.trim())
                            && "".equals(currentProvider.trim()) ){
                           continue;
                          }
                        
                          if ("".equals(customerFirstName.trim())){
                           writer.print("First Name cannot be blank for any records");
                              resp.flushBuffer();
                              errorReceived =true;
                              break;
                          }
                        
                          CustomerVOList.add(CustomerVO);
                       }
                       HttpSession session =  req.getSession();
                       session.setAttribute("importedCustmer", CustomerVOList);
                       if(!errorReceived){
                        writer.print("Customer Data IMPORT SUCCESS");
                       }
                       resp.flushBuffer();
                   }
               }
           } catch (Exception e) {
               resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                       "An error occurred while processing: " + e.getMessage());
           }
 
       } else {
           resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                           "Request contents type is not supported by the servlet.");
      }
      }
 }



Back to top

------------------------- We hope you got necessary Info On -----------------------------------------

File Upload Servlet DiskFileItemFactory ServletFileUpload


File Upload Servlet DiskFileItemFactory ServletFileUpload

-------------------------------------------------------------------------------------------------------



Face Book
Request for a Mock Interview/Training

Get a PDF

Face Book
Same look (Read) on any device, this is Ads free