Example usage for org.apache.commons.fileupload FileItem write

List of usage examples for org.apache.commons.fileupload FileItem write

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem write.

Prototype

void write(File file) throws Exception;

Source Link

Document

A convenience method to write an uploaded item to disk.

Usage

From source file:com.ephesoft.gxt.admin.server.DocumentTypeLearnFileServlet.java

@SuppressWarnings("unchecked")
private void attachFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    if (ServletFileUpload.isMultipartContent(req)) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        String exportSerailizationFolderPath = batchSchemaService.getBaseFolderLocation() + File.separator
                + "tempLearnFile";
        File exportSerailizationFolder = new File(exportSerailizationFolderPath);
        if (!exportSerailizationFolder.exists()) {
            exportSerailizationFolder.mkdirs();
        } else {//from   ww  w. jav  a 2s  .c  om
            FileUtils.deleteContents(exportSerailizationFolderPath, false);
            exportSerailizationFolder.mkdirs();
        }
        String learnFileName = null;
        String pathToLearnFile = null;
        String learnFileExtension = null;
        List<FileItem> items;

        try {
            items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    learnFileName = item.getName();

                    if (learnFileName != null) {
                        learnFileName = learnFileName.substring(learnFileName.lastIndexOf(File.separator) + 1);
                        learnFileExtension = learnFileName.substring(learnFileName.lastIndexOf(".") + 1);

                    }

                    pathToLearnFile = EphesoftStringUtil.concatenate(exportSerailizationFolderPath,
                            File.separator, learnFileName);

                    int numberOfPages = 0;

                    File learnedFile = new File(pathToLearnFile);
                    batchClassIdentifier = req.getParameter(DocumentTypeConstants.BATCH_CLASS_ID_REQ_PARAMETER);
                    documentType = req.getParameter(DocumentTypeConstants.DOCUMENT_TYPE_REQ_PARAMETER);

                    try {
                        item.write(learnedFile);
                        if (learnFileExtension.equalsIgnoreCase(FileType.PDF.getExtension())) {
                            numberOfPages = PDFUtil.getPDFPageCount(pathToLearnFile);

                            converPDFTotiffFile(pathToLearnFile, numberOfPages);
                            copySinglePageFilesToLearnFolder(exportSerailizationFolderPath, learnFileName);

                        } else if (learnFileExtension.equalsIgnoreCase(FileType.TIF.getExtension())
                                || learnFileExtension.equalsIgnoreCase(FileType.TIFF.getExtension())) {
                            numberOfPages = TIFFUtil.getTIFFPageCount(pathToLearnFile);
                            if (numberOfPages != 1) {
                                convertMultiPageTiffToSinglePageTiff(pathToLearnFile, numberOfPages);
                                copySinglePageFilesToLearnFolder(exportSerailizationFolderPath, learnFileName);
                            } else {
                                copyFilesFromTempToLearnFolders(exportSerailizationFolderPath, learnFileName,
                                        FIRST_PAGE);
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        } catch (FileUploadException e) {
            log.error("Unable to read the form contents." + e, e);
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.jena.JenaXMLFileUpload.java

/**
 * Save files to baseDirectoryForFiles and return a list of File objects.
 * @param fileStreams/*  ww  w  .j av  a  2s  . com*/
 * @return
 * @throws ServletException
 */
private List<File> saveFiles(Map<String, List<FileItem>> fileStreams) throws ServletException {
    // save files to disk
    List<File> filesToLoad = new ArrayList<File>();
    for (String fileItemKey : fileStreams.keySet()) {
        for (FileItem fileItem : fileStreams.get(fileItemKey)) {
            String originalName = fileItem.getName();
            String name = originalName.replaceAll("[,+\\\\/$%^&*#@!<>'\"~;]", "_");
            name = name.replace("..", "_");
            name = name.trim().toLowerCase();

            String saveLocation = baseDirectoryForFiles + File.separator + name;
            String savedName = name;
            int next = 0;
            boolean foundUnusedName = false;
            while (!foundUnusedName) {
                File test = new File(saveLocation);
                if (test.exists()) {
                    next++;
                    savedName = name + '(' + next + ')';
                    saveLocation = baseDirectoryForFiles + File.separator + savedName;
                } else {
                    foundUnusedName = true;
                }
            }

            File uploadedFile = new File(saveLocation);
            try {
                fileItem.write(uploadedFile);
            } catch (Exception ex) {
                log.error("Unable to save POSTed file. " + ex.getMessage());
                throw new ServletException("Unable to save file to the disk. " + ex.getMessage());
            }

            if (fileItem.getSize() < 1) {
                throw new ServletException("No file was uploaded or file was empty.");
            } else {
                filesToLoad.add(uploadedFile);
            }
        }
    }
    return filesToLoad;
}

From source file:com.arcadian.loginservlet.CourseContentServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }// w ww  .j a v a 2 s.  c  om
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        String materialid = "";
        String materialname = "";
        String subjectid = "";
        String classname = "";
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            if (fileItem.isFormField()) {

                String name = fileItem.getFieldName();
                System.out.println(name);

                String value = fileItem.getString();
                System.out.println(value);

                if (name.equalsIgnoreCase("materialid")) {
                    materialid = value;
                }
                if (name.equalsIgnoreCase("materialname")) {
                    materialname = value;
                }
                if (name.equalsIgnoreCase("subjectid")) {
                    subjectid = value;
                }
                if (name.equalsIgnoreCase("semname")) {
                    classname = value;
                }

            }

            if (fileItem.getName() != null) {

                File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                        + fileItem.getName());
                System.out.println("Absolute Path at server=" + file.getAbsolutePath());
                fileItem.write(file);

                contentService = new CourseContentService();
                contentService.updatecoursematerial(materialid, materialname, classname, subjectid, username,
                        fileItem.getName());
            }
        }

    } catch (FileUploadException e) {
        System.out.println("Exception in file upload" + e);
    } catch (Exception ex) {
        Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    processRequest(request, response);

}

From source file:jm.web.Archivo.java

/**
 * Sube un archivo del cliente al servidor Web. Si el archivo ya existe en el
 * servidor Web lo sobrescribe./*from   w  w w .j  a  v a 2 s  .  c  om*/
 * @param request. Variable que contiene el request de un formulario.
 * @param tamanioMax. Tamao mximo del archivo en megas.
 * @return Retorna true o false si se subi o no el archivo.
 */
public boolean subir(HttpServletRequest request, double tamanioMax, String[] formato) {
    boolean res = false;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String tipo = item.getContentType();
                    double tamanio = (double) item.getSize() / 1024 / 1024; // para tamao en megas
                    this._archivoNombre = item.getName().replace(" ", "_");
                    this._error = "Se ha excedido el tamao mximo del archivo";
                    if (tamanio <= tamanioMax) {
                        this._error = "El formato del archivo es incorrecto. " + tipo;
                        boolean estaFormato = false;
                        for (int i = 0; i < formato.length; i++) {
                            if (tipo.compareTo(formato[i]) == 0) {
                                estaFormato = true;
                                break;
                            }
                        }
                        if (estaFormato) {
                            this._archivo = new File(this._directorio, this._archivoNombre);
                            item.write(this._archivo);
                            this._error = "";
                            res = true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            this._error = e.getMessage();
            e.printStackTrace();
        }
    }
    return res;
}

From source file:com.arcadian.loginservlet.LecturesServlet.java

/**
 * Handles the HTTP/*  w  w w.j a  v  a 2  s  . c  o  m*/
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        String lectureid = "";
        String lecturename = "";
        String subjectid = "";
        String classname = "";
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            if (fileItem.isFormField()) {

                String name = fileItem.getFieldName();
                System.out.println(name);

                String value = fileItem.getString();
                System.out.println(value);

                if (name.equalsIgnoreCase("lectureid")) {
                    lectureid = value;
                }
                if (name.equalsIgnoreCase("lecturename")) {
                    lecturename = value;
                }
                if (name.equalsIgnoreCase("subjectid")) {
                    subjectid = value;
                }
                if (name.equalsIgnoreCase("semname")) {
                    classname = value;
                }

            }

            if (fileItem.getName() != null) {

                File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                        + fileItem.getName());
                System.out.println("Absolute Path at server=" + file.getAbsolutePath());
                fileItem.write(file);

                lecturesService = new LecturesService();
                lecturesService.updateLectures(lectureid, lecturename, classname, subjectid, username,
                        fileItem.getName());
            }
        }

    } catch (FileUploadException e) {
        System.out.println("Exception in file upload" + e);
    } catch (Exception ex) {
        Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    processRequest(request, response);
}

From source file:edu.pitt.servlets.processAddMedia.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w w w . j a v a2s  .c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    String userID = (String) session.getAttribute("userID");

    String error = "select correct format ";
    session.setAttribute("error", error);

    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        // Process only if its multipart content
        // Create a factory for disk-based file items
        File file;
        // We might need to play with the file sizes
        int maxFileSize = 50000 * 1024;
        int maxMemSize = 50000 * 1024;
        ServletContext context = this.getServletContext();
        // Note that this file path refers to a virtual path
        // relative to this servlet.  The uploads directory
        // is part of this project.  The physical path varies 
        // from the virtual path

        String filePath = context.getRealPath("/uploads") + "/";
        out.println("Physical folder is located at: " + filePath + "<br />");

        // Verify the content type
        String contentType = request.getContentType();
        // This is very important - make sure that the web form that 
        // uploads the file is actually set to enctype="multipart/form-data"
        // An example of upload form for this project is in index.html
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(filePath));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);
            try {
                // Parse the request to get file items.
                List fileItems = upload.parseRequest(request);

                // Process the uploaded file items
                Iterator i = fileItems.iterator();
                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        String fieldName = fi.getFieldName();

                        out.println("field name" + fieldName);
                        String fileName = fi.getName();

                        out.println("file name" + fileName); // file name is present

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        //  out.println("file size"+ sizeInBytes);
                        // Write the file
                        if (fileName.lastIndexOf("\\") >= 0) {
                            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                        } else {
                            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                        }
                        fi.write(file);
                        //  out.println("Uploaded Filename: " + filePath  + fileName + "<br />");
                        String savepath = filePath + fileName;

                        // to check correct format is entered or not 
                        int dotindex = fileName.indexOf(".");
                        if (!(fileName.substring(dotindex).matches(".ogv|.webm|.mp4|.png|.jpeg|.jpg|.gif"))) {
                            response.sendRedirect("./pages/addMedia.jsp");

                        }

                        // receives projectID from listProjects.jsp from edit href link , adding in existing project 
                        // corresponding constructor is used          
                        if (session.getAttribute("projectID") != null) {
                            Integer projectID = (Integer) session.getAttribute("projectID");

                            media = new Media(projectID, fileName);
                        }
                        // first time when user enters media for project , this constructor is used          
                        else {
                            media = new Media(userID, fileName);
                        }

                        System.out.println("Into the media constructor");
                        // redirected to listProject
                        response.sendRedirect("./pages/listProject.jsp");

                        // media constructor

                        // response.redirect(listprojects.jsp);

                        processRequest(request, response);
                    }

                }

            }

            catch (FileUploadException ex) {
                Logger.getLogger(processAddMedia.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(processAddMedia.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:AdminPackage.AdminAddProductController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w  ww  . j a v  a 2 s .  c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HProductDao pDao = new HProductDao();
    Product product = new Product();
    Categories c = new Categories();
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {

            FileItem item = iter.next();

            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                switch (name) {
                case "productName":
                    product.setProductName(value);
                    break;
                case "productDesc":
                    product.setProductDescription(value);
                    break;
                case "productPrice":
                    product.setProductPrice(Float.parseFloat(value));
                    break;
                case "productQuantityAvailable":
                    product.setProductQuntityavailable(Integer.parseInt(value));
                    break;
                case "productQuantitySold":
                    product.setProductQuntitysold(Integer.parseInt(value));
                    break;
                case "productCategory":
                    c.setIdcategory(Integer.parseInt(value));
                    product.setCategories(c);
                    break;
                }
            } else {
                if (!item.isFormField()) {
                    item.write(new File("C:/images/" + item.getName()));
                    product.setProductImg(item.getName());
                }
            }

        }
    } catch (FileUploadException ex) {
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    pDao.insert(product);
    /*     PrintWriter out = response.getWriter();
     out.write("Done");*/

    response.sendRedirect("/WebProjectServletJsp/AdminProductController");
}

From source file:com.krawler.esp.servlets.ExportImportContactsServlet.java

public static String uploadDocument(HttpServletRequest request, String fileid, String userId)
        throws ServiceException {
    String result = "";
    try {/*from www  .  j a  v  a  2 s  .c o  m*/
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importcontacts" + StorageHandler.GetFileSeparator() + userId;
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        org.apache.commons.fileupload.FileItem fi = null;
        org.apache.commons.fileupload.FileItem docTmpFI = null;

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
        }

        long size = 0;
        String Ext = "";
        String fileName = null;
        boolean fileupload = false;
        java.io.File destDir = new java.io.File(destinationDirectory);
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        java.util.HashMap arrParam = new java.util.HashMap();
        for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
            fi = (org.apache.commons.fileupload.FileItem) k.next();
            arrParam.put(fi.getFieldName(), fi.getString());
            if (!fi.isFormField()) {
                size = fi.getSize();
                fileName = new String(fi.getName().getBytes(), "UTF8");

                docTmpFI = fi;
                fileupload = true;
            }
        }

        if (fileupload) {

            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
            }
            if (size != 0) {
                File uploadFile = new File(destinationDirectory + "/" + fileid + Ext);
                docTmpFI.write(uploadFile);
                //                    fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size);
                result = fileid + Ext;
            }
        }
    } catch (ConfigurationException ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("ExportImportContactServlet.uploadDocument", ex);
    } catch (Exception ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("ExportImportContactServlet.uploadDocument", ex);
    }
    return result;
}

From source file:com.stratelia.webactiv.webSites.control.WebSiteSessionController.java

/**
 * Creates a web site from the content of an archive file (a ZIP file).
 *
 * @param descriptionSite the site to create.
 * @param fileItem the zip archive with the content of the site to create.
 * @return the creation status. 0 means the creation succeed, other values means the site creation
 * failed: -1 the main page name is invalid and -2 the web site folder creation failed.
 * @throws Exception if an unexpected error occurs when creating the web site.
 *//* w  w w . j  av  a2s.  co m*/
public int createWebSiteFromZipFile(SiteDetail descriptionSite, FileItem fileItem) throws Exception {
    /* Cration du directory */
    String cheminZip = getWebSiteRepositoryPath() + getWebSitePathById(descriptionSite.getId());
    File directory = new File(cheminZip);
    if (directory.mkdir()) {
        /* creation du zip sur le serveur */
        String fichierZipName = FileUploadUtil.getFileName(fileItem);
        File fichier = new File(cheminZip + "/" + fichierZipName);

        fileItem.write(fichier);

        /* dezip du fichier.zip sur le serveur */
        String cheminFichierZip = cheminZip + "/" + fichierZipName;
        unzip(cheminZip, cheminFichierZip);

        /* check the files are thoses expected */
        Collection<File> files = FileFolderManager.getAllWebPages(cheminZip);
        for (File uploadedFile : files) {
            if (!uploadedFile.getName().equals(fichierZipName) && !isInWhiteList(uploadedFile)) {
                return -3;
            }
        }

        /* verif que le nom de la page principale est correcte */
        Collection<File> collPages = getAllWebPages2(getWebSitePathById(descriptionSite.getId()));
        SilverTrace.debug("webSites", "RequestRouter.EffectiveUploadSiteZip", "root.MSG_GEN_PARAM_VALUE",
                collPages.size() + " files in zip");
        SilverTrace.debug("webSites", "RequestRouter.EffectiveUploadSiteZip", "root.MSG_GEN_PARAM_VALUE",
                "nomPage = " + descriptionSite.getContent());
        Iterator<File> j = collPages.iterator();
        boolean searchOk = false;
        File f;
        while (j.hasNext()) {
            f = j.next();
            SilverTrace.debug("webSites", "RequestRouter.EffectiveUploadSiteZip", "root.MSG_GEN_PARAM_VALUE",
                    "f.getName() = " + f.getName());
            if (f.getName().equals(descriptionSite.getContent())) {
                searchOk = true;
                break;
            }
        }

        if (!searchOk) {
            // le nom de la page principale n'est pas bonne
            return -1;
        }
    } else {
        return -2;
    }
    return 0;
}

From source file:com.primeleaf.krystal.web.action.console.NewDocumentAction.java

@SuppressWarnings("rawtypes")
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    String classId = request.getParameter("classid") != null ? request.getParameter("classid") : "0";

    if (request.getMethod().equalsIgnoreCase("POST")) {
        try {//from w w w.  ja  v  a2s  .c  om
            String userName = loggedInUser.getUserName();
            String sessionid = (String) session.getId();

            String tempFilePath = System.getProperty("java.io.tmpdir");

            if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) {
                tempFilePath += System.getProperty("file.separator");
            }
            tempFilePath += userName + "_" + sessionid;

            //variables
            String fileName = "", ext = "", comments = "";
            File file = null;
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING);

            //Create a file upload progress listener
            FileUploadProgressListener listener = new FileUploadProgressListener();
            upload.setProgressListener(listener);
            //put the listener in session
            session.setAttribute("LISTENER", listener);
            session.setAttribute("UPLOAD_ERROR", null);
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0));

            DocumentClass documentClass = null;

            Hashtable<String, String> indexRecord = new Hashtable<String, String>();
            String name = "";
            String value = "";

            List listItems = upload.parseRequest((HttpServletRequest) request);

            Iterator iter = listItems.iterator();
            FileItem fileItem = null;
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();
                if (fileItem.isFormField()) {
                    name = fileItem.getFieldName();
                    value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING);
                    if (name.equals("classid")) {
                        classId = value;
                    }
                    if (name.equals("txtNote")) {
                        comments = value;
                    }
                } else {
                    try {
                        fileName = fileItem.getName();
                        file = new File(fileName);
                        fileName = file.getName();
                        ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                        file = new File(tempFilePath + "." + ext);
                        fileItem.write(file);
                    } catch (Exception ex) {
                        session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage());
                        return null;
                    }
                }
            } //if

            if (file.length() <= 0) { //code for checking minimum size of file
                session.setAttribute("UPLOAD_ERROR", "Zero length document");
                return null;
            }
            documentClass = DocumentClassDAO.getInstance().readDocumentClassById(Integer.parseInt(classId));
            if (documentClass == null) {
                session.setAttribute("UPLOAD_ERROR", "Invalid document class");
                return null;
            }
            AccessControlManager aclManager = new AccessControlManager();
            ACL acl = aclManager.getACL(documentClass, loggedInUser);

            if (!acl.canCreate()) {
                session.setAttribute("UPLOAD_ERROR", "Access Denied");
                return null;
            }

            long usedStorage = DocumentDAO.getInstance().documentSize();
            long availableStorage = ServerConstants.MAX_STORAGE - usedStorage;

            if (file.length() > availableStorage) {
                session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0));
                session.setAttribute("UPLOAD_ERROR", "Document upload failed. Storage limit exceeded.");
                return null;
            }
            String indexValue = "";
            String indexName = "";
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(50));

            for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) {
                indexName = indexDefinition.getIndexColumnName();
                Iterator iter1 = listItems.iterator();
                while (iter1.hasNext()) {
                    FileItem item1 = (FileItem) iter1.next();
                    if (item1.isFormField()) {
                        name = item1.getFieldName();
                        value = item1.getString(HTTPConstants.CHARACTER_ENCODING);
                        if (name.equals(indexName)) {
                            indexValue = value;
                            String errorMessage = "";
                            if (indexValue != null) {
                                if (indexDefinition.isMandatory()) {
                                    if (indexValue.trim().length() <= 0) {
                                        errorMessage = "Invalid input for "
                                                + indexDefinition.getIndexDisplayName();
                                        session.setAttribute("UPLOAD_ERROR", errorMessage);
                                        return null;
                                    }
                                }
                                if (IndexDefinition.INDEXTYPE_NUMBER
                                        .equalsIgnoreCase(indexDefinition.getIndexType())) {
                                    if (indexValue.trim().length() > 0) {
                                        if (!GenericValidator.matchRegexp(indexValue,
                                                HTTPConstants.NUMERIC_REGEXP)) {
                                            errorMessage = "Invalid input for "
                                                    + indexDefinition.getIndexDisplayName();
                                            session.setAttribute("UPLOAD_ERROR", errorMessage);
                                            return null;
                                        }
                                    }
                                } else if (IndexDefinition.INDEXTYPE_DATE
                                        .equalsIgnoreCase(indexDefinition.getIndexType())) {
                                    if (indexValue.trim().length() > 0) {
                                        if (!GenericValidator.isDate(indexValue, "yyyy-MM-dd", true)) {
                                            errorMessage = "Invalid input for "
                                                    + indexDefinition.getIndexDisplayName();
                                            session.setAttribute("UPLOAD_ERROR", errorMessage);
                                            return null;
                                        }
                                    }
                                }
                                if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking index field length
                                    errorMessage = "Document index size exceeded for " + "Index Name : "
                                            + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : "
                                            + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : "
                                            + indexValue.length() + " ]";
                                    session.setAttribute("UPLOAD_ERROR", errorMessage);
                                    return null;
                                }
                            }
                            indexRecord.put(indexName, indexValue);
                        }
                    }
                } //while iter
            } //while indexCfgList
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(70));

            DocumentRevision documentRevision = new DocumentRevision();
            documentRevision.setClassId(documentClass.getClassId());
            documentRevision.setDocumentId(0);
            documentRevision.setRevisionId("1.0");
            documentRevision.setDocumentFile(file);
            documentRevision.setUserName(loggedInUser.getUserName());
            documentRevision.setIndexRecord(indexRecord);
            documentRevision.setComments(comments);

            DocumentManager documentManager = new DocumentManager();
            documentManager.storeDocument(documentRevision, documentClass);

            //Log the entry to audit logs 
            AuditLogManager.log(new AuditLogRecord(documentRevision.getDocumentId(),
                    AuditLogRecord.OBJECT_DOCUMENT, AuditLogRecord.ACTION_CREATED, userName,
                    request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Document created"));

            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(100));
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        return null;
    } else {
        try {
            ArrayList<DocumentClass> availableDocumentClasses = DocumentClassDAO.getInstance()
                    .readDocumentClasses(" ACTIVE = 'Y'");
            ArrayList<DocumentClass> documentClasses = new ArrayList<DocumentClass>();
            AccessControlManager aclManager = new AccessControlManager();
            for (DocumentClass documentClass : availableDocumentClasses) {
                ACL acl = aclManager.getACL(documentClass, loggedInUser);
                if (acl.canCreate()) {
                    documentClasses.add(documentClass);
                }
            }
            int documentClassId = 0;
            try {
                documentClassId = Integer.parseInt(classId);
            } catch (Exception ex) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
                return (new NewDocumentView(request, response));
            }
            if (documentClassId > 0) {
                DocumentClass selectedDocumentClass = DocumentClassDAO.getInstance()
                        .readDocumentClassById(documentClassId);
                request.setAttribute("DOCUMENTCLASS", selectedDocumentClass);
            }
            request.setAttribute("CLASSID", documentClassId);
            request.setAttribute("CLASSLIST", documentClasses);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return (new NewDocumentView(request, response));
}