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

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

Introduction

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

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:it.infn.ct.SemanticSearch_portlet.java

public void getInputForm(ActionRequest request, App_Input appInput) {
    if (PortletFileUpload.isMultipartContent(request)) {
        try {/*  w ww .  j a va  2 s .  com*/
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {

                case JobIdentifier:
                    appInput.jobIdentifier = item.getString();
                    break;
                default:
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName                                                   
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    } // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        appInput.search_word = (String) request.getParameter("search_word");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");
        appInput.nameSubject = (String) request.getParameter("nameSubject");

        appInput.idResouce = (String) request.getParameter("idResource");
        appInput.selected_language = (String) request.getParameter("selLanguage");
        appInput.numberPage = (String) request.getParameter("numberOfPage");
        appInput.numRecordsForPage = (String) request.getParameter("numberOfRecords");
        appInput.title_GS = (String) request.getParameter("title_GS");
        appInput.moreInfo = (String) request.getParameter("moreInfo");
        if (appInput.selected_language == null) {
            appInput.selected_language = (String) request.getParameter("nameLanguageDefault");
        }
    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "Search Word: '"
            + appInput.search_word + "'" + LS + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS
            + "subject: '" + appInput.nameSubject + "'" + LS + "idResource: '" + appInput.idResouce + "'" + LS
            + "language selected: '" + appInput.selected_language + "'" + LS + "number page selected: '"
            + appInput.numberPage + "'" + LS + "number record for page: '" + appInput.numRecordsForPage + "'"
            + LS + "moreInfo: '" + appInput.moreInfo + "'" + LS);
}

From source file:it.biblio.servlets.Inserimento_Ristampa.java

/**
 * metodo per gestire l'upload di file// ww  w  .j  a  v a  2  s  .  c  o m
 *
 * @param request
 * @param response
 * @param k
 * @return
 * @throws IOException
 */
private boolean upload(HttpServletRequest request) throws IOException, Exception {

    Map<String, Object> ristampe = new HashMap<String, Object>();
    int idopera = Integer.parseInt(request.getParameter("id"));

    if (ServletFileUpload.isMultipartContent(request)) {

        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfo = new ServletFileUpload(fif);
        List<FileItem> items = sfo.parseRequest(request);
        for (FileItem item : items) {
            String fname = item.getFieldName();
            if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) {
                ristampe.put("numpagine", Integer.parseInt(item.getString()));
            } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) {
                ristampe.put("datapub", item.getString());
            } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) {
                ristampe.put("editore", item.getString());
            } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) {
                ristampe.put("lingua", item.getString());
            } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) {
                ristampe.put("indice", item.getString());
                //se  stato inserito un pdf salvo il file e inserisco nella mappa i dati
            } else if (!item.isFormField() && fname.equals("PDF")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF"
                            + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("download", "PDF" + File.separatorChar + name);
                }
                //salvo l'immagine e inserisco i dati nella mappa
            } else if (!item.isFormField() && fname.equals("copertina")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar
                            + "Copertine" + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("copertina", "Copertine" + File.separatorChar + name);
                }
            }
        }
        ristampe.put("pubblicazioni", idopera);
        return Database.insertRecord("ristampe", ristampe);

    }
    return false;
}

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/*from ww w  .java 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:edu.xtec.colex.client.beans.ColexRecordBean.java

/**
 * Parses the parameters and calls the web service operation
 *
 * @throws java.lang.Exception when an Exception error occurs
 *//*  ww w. j  a  v  a  2  s  .  c o m*/
protected void parseModifyRecord() throws Exception {
    java.util.Enumeration e = pmRequest.getParameterNames();

    Vector vAttachments = new Vector();

    getStructure();

    Record r = new Record();
    r.setId(Integer.parseInt(pmRequest.getParameter("idRecord")));
    Field fAux;
    String paramName;
    String fieldType;
    String fieldName;
    String fieldId;

    while (e.hasMoreElements()) {
        paramName = (String) e.nextElement();
        fAux = new Field();

        if (paramName.startsWith("fd_")) {
            fieldId = paramName.substring(3);
            fieldName = ((FieldDef) vFieldDefs.get(Integer.parseInt(fieldId))).getName();
            fieldType = getFieldDef(fieldName).getType();

            if (fieldType.equals("image") || fieldType.equals("sound")) {
                FileItem fi = pmRequest.getFileItem(paramName);
                String sNomFitxer;

                if (pmRequest.getParameter("del_" + fieldId).equals("true")) {
                    sNomFitxer = "delete";
                } else if (fi.getSize() != 0) //case there is no attachment
                {
                    sNomFitxer = Utils.getFileName(fi.getName());
                    fi.setFieldName(fieldName);

                    vAttachments.add(fi);
                } else {
                    sNomFitxer = "null";
                }

                fAux.setName(fieldName);
                fAux.setValue(sNomFitxer);

            } else {
                fAux.setName(fieldName);
                fAux.setValue(pmRequest.getParameter(paramName));
            }

            r.addField(fAux);

        } else if (paramName.startsWith("fdYYYY_")) {
            fieldId = paramName.substring(7);
            fieldName = ((FieldDef) vFieldDefs.get(Integer.parseInt(fieldId))).getName();

            String sDay = pmRequest.getParameter("fdDD_" + fieldId);
            String sMonth = pmRequest.getParameter("fdMM_" + fieldId);
            String sYear = pmRequest.getParameter("fdYYYY_" + fieldId);
            fAux.setName(fieldName);
            fAux.setValue(sYear + "-" + sMonth + "-" + sDay);
            r.addField(fAux);
        }

    }
    modifyRecord(r, vAttachments);
}

From source file:com.controller.UploadLogo.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w  w .j  a va  2 s . co m*/
 *
 * @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
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    getSqlMethodsInstance().session = request.getSession();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, uploadType = null;
    RequestDispatcher request_dispatcher = null;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        uploadPath = AppConstants.USER_LOGO;

        // Verify the content type
        String contentType = request.getContentType();

        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(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                boolean ch = fi.isFormField();

                if (!fi.isFormField()) {

                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    String uid = (String) getSqlMethodsInstance().session.getAttribute("EmailID");

                    int UID = getSqlMethodsInstance().getUserID(uid);
                    uploadPath = uploadPath + File.separator + UID + File.separator + "logo";

                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }

                    //                                int inStr = fileName.indexOf(".");
                    //                                String Str = fileName.substring(0, inStr);
                    //
                    //                                fileName = Str + "_" + UID + ".jpeg";
                    fileName = fileName + "_" + UID;
                    getSqlMethodsInstance().session.setAttribute("UID", UID);
                    getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName);
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);
                    fi.write(storeFile);

                    getSqlMethodsInstance().updateUsers(UID, fileName);
                    out.println("Uploaded Filename: " + filePath + "<br>");
                }

            }
        }

    } catch (Exception ex) {
        logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));

        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
        getSqlMethodsInstance().closeConnection();
    }

}

From source file:net.hillsdon.reviki.web.pages.impl.DefaultPageImpl.java

public View attach(final PageReference page, final ConsumedPath path, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new InvalidInputException("multipart request expected.");
    }/*from w  ww . j a va2  s  .c om*/
    List<FileItem> items = getFileItems(request);
    try {
        if (items.size() > 4) {
            throw new InvalidInputException("One file at a time.");
        }
        String attachmentName = null;
        Long baseRevision = null;
        String attachmentMessage = null;
        FileItem file = null;
        for (FileItem item : items) {
            if (PARAM_ATTACHMENT_NAME.equals(item.getFieldName())) {
                attachmentName = item.getString().trim();
            }
            if (PARAM_BASE_REVISION.equals(item.getFieldName())) {
                baseRevision = RequestParameterReaders.getLong(item.getString().trim(), PARAM_BASE_REVISION);
            }
            if (PARAM_ATTACHMENT_MESSAGE.equals(item.getFieldName())) {
                attachmentMessage = item.getString().trim();
                if (attachmentMessage.length() == 0) {
                    attachmentMessage = null;
                }
            }
            if (!item.isFormField()) {
                file = item;
            }
        }
        if (baseRevision == null) {
            baseRevision = VersionedPageInfo.UNCOMMITTED;
        }

        if (file == null || file.getSize() == 0) {
            request.setAttribute("flash", ERROR_NO_FILE);
            return attachments(page, path, request, response);
        } else {
            InputStream in = file.getInputStream();
            try {
                // get the page from store - needed to get content of the special
                // pages which were not saved yet
                PageInfo pageInfo = _store.get(page, -1);
                // IE sends the full file path.
                storeAttachment(pageInfo, attachmentName, baseRevision, attachmentMessage,
                        FilenameUtils.getName(file.getName()), in);
                _store.expire(pageInfo);
                return new RedirectToPageView(_wikiUrls, page, "/attachments/");
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } finally {
        for (FileItem item : items) {
            item.delete();
        }
    }
}

From source file:com.nartex.RichFileManager.java

@Override
public JSONObject add() {
    JSONObject fileInfo = new JSONObject();
    Iterator<FileItem> it = this.files.iterator();
    String mode = "";
    String currentPath = "";
    boolean error = false;
    long size = 0;
    if (!it.hasNext()) {
        fileInfo = this.uploadError(lang("INVALID_FILE_UPLOAD"));
    } else {//from   w w  w  .ja  v a2  s.  c o m
        String allowed[] = { ".", "-" };
        String fileName = "";
        FileItem targetItem = null;
        try {
            while (it.hasNext()) {
                FileItem item = it.next();
                if (item.isFormField()) {
                    if (item.getFieldName().equals("mode")) {
                        mode = item.getString();
                        // v1.0.6 renamed mode add to upload
                        if (!mode.equals("upload") && !mode.equals("add") && !mode.equals("replace")) {
                            //this.error(lang("INVALID_FILE_UPLOAD"));
                        }
                    } else if (item.getFieldName().equals("currentpath")) {
                        currentPath = item.getString();
                    } else if (item.getFieldName().equals("newfilepath")) {
                        currentPath = item.getString();
                    }
                } else if (item.getFieldName().equals("files")) { // replace
                    //replace= true;
                    size = item.getSize();
                    targetItem = item;
                    // v1.0.6 renamed mode add to upload
                    if (mode.equals("add") || mode.equals("upload")) {
                        fileName = item.getName();
                        // set fileName
                    }
                } else if (item.getFieldName().equals("newfile")) {
                    fileName = item.getName();
                    // strip possible directory (IE)
                    int pos = fileName.lastIndexOf(File.separator);
                    if (pos > 0) {
                        fileName = fileName.substring(pos + 1);
                    }
                    size = item.getSize();
                    targetItem = item;
                }
            }
            if (!error) {
                if (mode.equals("replace")) {
                    String tmp[] = currentPath.split("/");
                    fileName = tmp[tmp.length - 1];
                    int pos = fileName.lastIndexOf(File.separator);
                    if (pos > 0)
                        fileName = fileName.substring(pos + 1);
                    if (fileName != null) {
                        currentPath = currentPath.replace(fileName, "");
                        currentPath = currentPath.replace("//", "/");
                    }
                } else {
                    if (!isImage(fileName) && (config.getProperty("upload-imagesonly") != null
                            && config.getProperty("upload-imagesonly").equals("true")
                            || this.params.get("type") != null && this.params.get("type").equals("Image"))) {
                        fileInfo = this.uploadError(lang("UPLOAD_IMAGES_ONLY"));
                        error = true;
                    }
                    LinkedHashMap<String, String> strList = new LinkedHashMap<String, String>();
                    strList.put("fileName", fileName);
                    fileName = cleanString(strList, allowed).get("fileName");
                }
                long maxSize = 0;
                if (config.getProperty("upload-size") != null) {
                    maxSize = Integer.parseInt(config.getProperty("upload-size"));
                    if (maxSize != 0 && size > (maxSize * 1024 * 1024)) {
                        fileInfo = this.uploadError(sprintf(lang("UPLOAD_FILES_SMALLER_THAN"), maxSize + "Mb"));
                        error = true;
                    }
                }
                if (!error) {
                    currentPath = cleanPreview(currentPath.replaceFirst("^/", ""));// relative
                    Path path = currentPath.equals("") ? this.documentRoot
                            : this.documentRoot.resolve(currentPath);
                    if (config.getProperty("upload-overwrite").toLowerCase().equals("false")) {
                        fileName = this.checkFilename(path.toString(), fileName, 0);
                    }
                    if (mode.equals("replace")) {
                        File saveTo = path.resolve(fileName).toFile();
                        targetItem.write(saveTo);
                        log.info("saved " + saveTo);
                    } else {
                        fileName = fileName.replace("//", "/").replaceFirst("^/", "");// relative
                        File saveTo = path.resolve(fileName).toFile();
                        targetItem.write(saveTo);
                        log.info("saved " + saveTo);
                    }
                    fileInfo.put("Path", getPreviewFolder() + currentPath);
                    fileInfo.put("Name", fileName);
                    fileInfo.put("Error", "");
                    fileInfo.put("Code", 0);
                }
            }
        } catch (Exception e) {
            fileInfo = this.uploadError(lang("INVALID_FILE_UPLOAD"));
        }
    }
    return fileInfo;
}

From source file:com.controller.changeLogo.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  ww  .  ja va 2 s  . c  o m
 *
 * @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
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    getSqlMethodsInstance().session = request.getSession();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, uploadType = null;
    RequestDispatcher request_dispatcher = null;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        uploadPath = AppConstants.USER_LOGO;

        // Verify the content type
        String contentType = request.getContentType();

        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(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("upload")) {
                        uploadType = fi.getString();
                    }

                } else {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    Integer UID = (Integer) getSqlMethodsInstance().session.getAttribute("UID");

                    uploadPath = uploadPath + File.separator + UID + File.separator + "logo";

                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }

                    //                                int inStr = fileName.indexOf(".");
                    //                                String Str = fileName.substring(0, inStr);
                    //
                    //                                fileName = Str + "_" + UID + ".jpeg";
                    fileName = fileName + "_" + UID;
                    getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName);
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    if (uploadType.equals("update")) {
                        String file_name_to_delete = getSqlMethodsInstance().getLogofileName(UID);
                        String filePath_to_delete = uploadPath + File.separator + file_name_to_delete;

                        File deletefile = new File(filePath_to_delete);
                        deletefile.delete();
                    }

                    filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);
                    fi.write(storeFile);

                    getSqlMethodsInstance().updateUsers(UID, fileName);
                    out.println("Uploaded Filename: " + filePath + "<br>");

                    response.sendRedirect(request.getContextPath() + "/settings.jsp");

                }

            }
        }

    } catch (Exception ex) {
        logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));

        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
        getSqlMethodsInstance().closeConnection();
    }

}

From source file:admin.controller.ServletAddPersonality.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w.ja  va  2 s  . c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        String uploadPath = AppConstants.BRAND_IMAGES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        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("/tmp"));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("brandname")) {
                        brand_name = fi.getString();
                    }
                    if (field_name.equals("look")) {
                        look_id = fi.getString();
                    }

                } else {
                    check = brand.checkAvailability(brand_name);

                    if (check == false) {
                        field_name = fi.getFieldName();
                        file_name = fi.getName();

                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                                int inStr = file_name.indexOf(".");
                        //                                String Str = file_name.substring(0, inStr);
                        //                                file_name = brand_name + "_" + Str + ".jpeg";

                        file_name = brand_name + "_" + file_name;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String filePath = uploadPath + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);
                        brand.addBrands(brand_name, Integer.parseInt(look_id), file_name);

                        response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp");

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    } else {
                        response.sendRedirect(
                                request.getContextPath() + "/admin/brandpersonality.jsp?exist=exist");
                    }
                }
            }
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
        }
    }

}

From source file:com.enonic.cms.web.portal.services.ServicesProcessorBase.java

private ExtendedMap parseMultiPartRequest(HttpServletRequest request) {
    ExtendedMap formItems = new ExtendedMap(true);
    try {/*from   w  w w  .  j av  a2 s  . c o m*/
        List paramList = fileUpload.parseRequest(new ServletRequestContext(request));
        for (Iterator iter = paramList.iterator(); iter.hasNext();) {
            FileItem fileItem = (FileItem) iter.next();

            String name = fileItem.getFieldName();

            if (fileItem.isFormField()) {
                String value = fileItem.getString("UTF-8");
                if (formItems.containsKey(name)) {
                    ArrayList<Object> values = new ArrayList<Object>();
                    Object obj = formItems.get(name);
                    if (obj instanceof Object[]) {
                        String[] objArray = (String[]) obj;
                        for (int i = 0; i < objArray.length; i++) {
                            values.add(objArray[i]);
                        }
                    } else {
                        values.add(obj);
                    }
                    values.add(value);
                    formItems.put(name, values.toArray(new String[values.size()]));
                } else {
                    formItems.put(name, value);
                }
            } else {
                if (fileItem.getSize() > 0) {
                    if (formItems.containsKey(name)) {
                        ArrayList<Object> values = new ArrayList<Object>();
                        Object obj = formItems.get(name);
                        if (obj instanceof FileItem[]) {
                            FileItem[] objArray = (FileItem[]) obj;
                            for (int i = 0; i < objArray.length; i++) {
                                values.add(objArray[i]);
                            }
                        } else {
                            values.add(obj);
                        }
                        values.add(fileItem);
                        formItems.put(name, values.toArray(new FileItem[values.size()]));
                    } else {
                        formItems.put(name, fileItem);
                    }
                }
            }
        }
    } catch (FileUploadException fue) {
        String message = "Error occurred with file upload: %t";
        VerticalAdminLogger.error(message, fue);
    } catch (UnsupportedEncodingException uee) {
        String message = "Character encoding not supported: %t";
        VerticalAdminLogger.error(message, uee);
    }

    // Add parameters from url
    Map paramMap = request.getParameterMap();
    for (Iterator iter = paramMap.entrySet().iterator(); iter.hasNext();) {
        Map.Entry entry = (Map.Entry) iter.next();
        String key = (String) entry.getKey();
        if (entry.getValue() instanceof String[]) {
            String[] values = (String[]) entry.getValue();
            for (int i = 0; i < values.length; i++) {
                formItems.put(key, values[i]);
            }
        } else {
            formItems.put(key, entry.getValue());
        }
    }

    return formItems;
}