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

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

Introduction

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

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

From source file:com.company.project.web.controller.FileUploadController.java

@RequestMapping(value = "/asyncUpload2", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody//from   w  w w  .  j  ava2  s.  c om
public ResponseEntity<String> asyncFileUpload2(HttpServletRequest request) throws Exception {
    MultipartHttpServletRequest mpr = (MultipartHttpServletRequest) request;
    if (request instanceof MultipartHttpServletRequest) {
        CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("fileUpload");
        List<MultipartFile> fs = (List<MultipartFile>) mpr.getFiles("fileUpload");
        System.out.println("f: " + f);

        for (String key : mpr.getParameterMap().keySet()) {
            System.out.println("Param Key: " + key + "\n Value: " + mpr.getParameterMap().get(key));
        }

        for (String key : mpr.getMultiFileMap().keySet()) {
            System.out.println("xParam Key: " + key + "\n xValue: " + mpr.getMultiFileMap().get(key));
        }

    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    Map<String, Object> parameterMap = new HashMap<>();
    Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");

    //if(request.getContentType().contains("multipart/form-data")){ 

    if (ServletFileUpload.isMultipartContent(request)) {
        Map<String, Object> map = new HashMap<>();
        List<FileItem> filefields = new ArrayList<>();
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) { //contentType: "image/jpeg", isFormField: false, fileName: "Chrysanthemum.jpg"
            if (item.isFormField()) {
                formfields.put(item.getFieldName(), item.getString());
            } else {
                filefields.add(item);
            }
        }

        parameterMap.put("filefields", filefields);
    }

    return new ResponseEntity<>("success", HttpStatus.OK);
}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.ImportBatchClassUploadServlet.java

private void attachFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService,
        DeploymentService deploymentService, BatchClassService bcService, ImportBatchService imService)
        throws IOException {
    PrintWriter printWriter = resp.getWriter();
    File tempZipFile = null;//from   w w  w .  j  av a  2 s . com
    InputStream instream = null;
    OutputStream out = null;
    String zipWorkFlowName = BatchClassManagementConstants.EMPTY_STRING,
            tempOutputUnZipDir = BatchClassManagementConstants.EMPTY_STRING,
            systemFolderPath = BatchClassManagementConstants.EMPTY_STRING;
    BatchClass importBatchClass = null;
    if (ServletFileUpload.isMultipartContent(req)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();
        File exportSerailizationFolder = new File(exportSerailizationFolderPath);
        if (!exportSerailizationFolder.exists()) {
            exportSerailizationFolder.mkdir();
        }
        String zipFileName = BatchClassManagementConstants.EMPTY_STRING;
        String zipPathname = BatchClassManagementConstants.EMPTY_STRING;
        List<FileItem> items;
        try {
            items = (List<FileItem>) upload.parseRequest(req);
            for (FileItem item : items) {
                if (!item.isFormField() && "importFile".equals(item.getFieldName())) {
                    zipFileName = item.getName();
                    if (zipFileName != null) {
                        zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1);
                    }
                    zipPathname = exportSerailizationFolderPath + File.separator + zipFileName;
                    if (zipFileName != null) {
                        zipFileName = FilenameUtils.getName(zipFileName);
                    }
                    try {
                        instream = item.getInputStream();
                        tempZipFile = new File(zipPathname);
                        if (tempZipFile.exists()) {
                            tempZipFile.delete();
                        }
                        out = new FileOutputStream(tempZipFile);
                        byte buf[] = new byte[BatchClassManagementConstants.BUFFER_SIZE];
                        int len = instream.read(buf);
                        while ((len) > 0) {
                            out.write(buf, 0, len);
                            len = instream.read(buf);
                        }
                    } catch (FileNotFoundException e) {
                        LOG.error("Unable to create the export folder." + e, e);
                        printWriter.write("Unable to create the export folder.Please try again.");

                    } catch (IOException e) {
                        LOG.error("Unable to read the file." + e, e);
                        printWriter.write("Unable to read the file.Please try again.");
                    } finally {
                        IOUtils.closeQuietly(out);
                        IOUtils.closeQuietly(instream);
                    }
                }
            }
        } catch (FileUploadException e) {
            LOG.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        }
        tempOutputUnZipDir = exportSerailizationFolderPath + File.separator
                + zipFileName.substring(0, zipFileName.lastIndexOf('.'));
        try {
            FileUtils.unzip(tempZipFile, tempOutputUnZipDir);
        } catch (Exception e) {
            LOG.error("Unable to unzip the file." + e, e);
            printWriter.write("Unable to unzip the file.Please try again.");
            tempZipFile.delete();
        }
        String serializableFilePath = FileUtils.getFileNameOfTypeFromFolder(tempOutputUnZipDir,
                SERIALIZATION_EXT);
        InputStream serializableFileStream = null;
        try {
            serializableFileStream = new FileInputStream(serializableFilePath);
            importBatchClass = (BatchClass) SerializationUtils.deserialize(serializableFileStream);
            zipWorkFlowName = importBatchClass.getName();
            systemFolderPath = importBatchClass.getSystemFolder();
            if (systemFolderPath == null) {
                systemFolderPath = BatchClassManagementConstants.EMPTY_STRING;
            }
        } catch (Exception e) {
            tempZipFile.delete();
            LOG.error("Error while importing" + e, e);
            printWriter.write("Error while importing.Please try again.");
        } finally {
            IOUtils.closeQuietly(serializableFileStream);
        }
    } else {
        LOG.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }
    if (tempZipFile != null) {
        tempZipFile.delete();
    }
    List<String> uncList = bcService.getAssociatedUNCList(zipWorkFlowName);
    boolean isWorkflowDeployed = deploymentService.isDeployed(zipWorkFlowName);
    boolean isWorkflowEqual = imService.isImportWorkflowEqualDeployedWorkflow(importBatchClass,
            importBatchClass.getName());
    printWriterMethod(printWriter, zipWorkFlowName, tempOutputUnZipDir, systemFolderPath, uncList,
            isWorkflowDeployed, isWorkflowEqual);
}

From source file:gov.nih.nci.caarray.web.fileupload.MonitoredMultiPartRequest.java

/**
 * {@inheritDoc}/*from   w  w  w  .  j  a va  2s.com*/
 */
@SuppressWarnings({ "unchecked", "PMD.CyclomaticComplexity" })
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    fac.setSizeThreshold(0);
    if (saveDir != null) {
        fac.setRepository(new File(saveDir));
    }
    ProgressMonitor monitor = null;
    try {
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);
        monitor = new ProgressMonitor();
        upload.setProgressListener(monitor);
        String uploadKey = getUploadKey(servletRequest);
        servletRequest.getSession().setAttribute(uploadKey, monitor);
        List<FileItem> items = (List<FileItem>) upload.parseRequest(createRequestContext(servletRequest));
        for (FileItem item : items) {
            LOG.debug((new StringBuilder()).append("Found item ").append(item.getFieldName()).toString());
            if (item.isFormField()) {
                handleFormField(servletRequest, item);
            } else {
                handleFileUpload(item);
            }
        }
        handleChunkedUploadHeaders(servletRequest);
    } catch (FileUploadException e) {
        if (monitor != null) {
            monitor.abort();
        }
        LOG.warn("Error processing upload", e);
        errors.add(e.getMessage());
    }
}

From source file:com.controller.RecipeImage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww w .  jav  a2  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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    //retrieving the path to store image from web.xml
    filePath = getServletContext().getInitParameter("recipeImageStorePath");

    //retrieving the path to display image from web.xml
    fileDisplay = getServletContext().getInitParameter("recipeImageDisplayPath");

    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        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>");
        return;
    }
    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("c:\\temp"));

    // 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();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("1");
        while (i.hasNext()) {
            out.println("2");
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                fileName = randomString(fileName);
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // 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: " + fileName + "<br>" + filePath);
            } else {
                out.println("No file");
            }
        }
        out.println("</body>");
        out.println("</html>");

        RecipeBean recipeBean = new RecipeBean();
        RecipeDAO recipeDAO = new RecipeDAO();

        String image = fileDisplay + "" + fileName;
        out.println(image);

        HttpSession session = request.getSession();
        String recipeId = (String) session.getAttribute("recipeId");
        session.removeAttribute("recipeId");
        recipeDAO.addImage(recipeId, image);

        response.sendRedirect("Home");

    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:controller.ControlPembayaran.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(Calendar.getInstance().getTime());
    String timeStamp2 = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());

    Pembayaran p = new Pembayaran();
    DatabaseManager db = new DatabaseManager();

    //Menyimpan file ke dalam sistem
    File file;/*from  w w  w.ja va 2s  .  c  o m*/
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    String filePath = "c:/Apache/";

    String contentType = request.getContentType();
    if (contentType.indexOf("multipart/form-data") >= 0) {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxFileSize);
        try {
            List fileItems = upload.parseRequest(request);
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    if (fi.getName().contains(".csv")) {
                        String fieldName = fi.getFieldName();
                        String fileName = fi.getName();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        file = new File(filePath + "DataPembayaran_" + timeStamp + ".csv");
                        fi.write(file);
                    } else {
                        throw new Exception("Format File Salah");
                    }
                }
            }
        } catch (Exception ex) {
            returnError(request, response, ex);
        }
    } else {
        Exception e = new Exception("no file uploaded");
        returnError(request, response, e);
    }
    //Membaca file dari dalam sistem
    String csvFile = filePath + "DataPembayaran_" + timeStamp + ".csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {
        br = new BufferedReader(new FileReader(csvFile));
        int counter = 1;
        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] dataSet = line.split(cvsSplitBy);
            p.setID(timeStamp2 + "_" + counter);
            p.setWaktuPembayaran(dataSet[0]);
            p.setNoRekening(dataSet[1]);
            p.setJumlahPembayaran(Double.parseDouble(dataSet[2]));
            p.setNis(dataSet[3].substring(0, 5));
            p.setBulanTagihan(Integer.parseInt(dataSet[3].substring(6)));
            //Membandingkan nis, jumlah, bulan pembayaran ke tagihan
            Tagihan[] t = Tagihan.getListTagihan(p.getNis());
            for (int i = 0; i < t.length; i++) {
                if (t[i].getNis().equals(p.getNis()) && t[i].getJumlah_pembayaran() == p.getJumlahPembayaran()
                        && t[i].getBulan_tagihan() == p.getBulanTagihan())// bandingkan jumlah pembayaran
                {
                    //Masukan data pembayaran ke database
                    Pembayaran.simpanPembayaran(p);
                    //update status pembayaran tagihan
                    t[i].verifikasiSukses(p.getNis(), p.getBulanTagihan());//update status bayar tagihan menjadi sudah bayar
                }
            }
            counter++;
        }
        this.tampil(request, response, "Data Terverifikasi");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //        }
}

From source file:it.unisa.tirocinio.servlet.UploadInformationFilesServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  w  w  . j a v  a  2 s. com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, JSONException {

    try {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        out = response.getWriter();
        isMultipart = ServletFileUpload.isMultipartContent(request);
        StudentDBOperation getSerialNumberObj = new StudentDBOperation();
        ConcreteStudent aStudent = null;
        String serialNumber = null;
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        File fileToStore = null;
        String studentSubfolderPath = filePath;
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                if (fieldName.equals("cvfile")) {
                    fileToStore = new File(studentSubfolderPath + fileSeparator + "CV.pdf");
                } else if (fieldName.equals("examsfile")) {
                    fileToStore = new File(studentSubfolderPath + fileSeparator + "ES.pdf");
                }
                fi.write(fileToStore);
                // out.println("Uploaded Filename: " + fieldName + "<br>");
            } else {
                //out.println("It's not formfield");
                //out.println(fi.getString());
                aStudent = getSerialNumberObj.getSerialNumberbyFK_Account(Integer.parseInt(fi.getString()));
                serialNumber = reverseSerialNumber(aStudent.getPrimaryKey());
                studentSubfolderPath += fileSeparator + serialNumber;
                new File(studentSubfolderPath).mkdir();
            }
        }
        message.put("status", 1);
        out.print(message.toString());
    } catch (IOException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileUploadException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:net.morphbank.mbsvc3.webservices.RestfulService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    MorphbankConfig.SYSTEM_LOGGER.info("starting post");
    response.setContentType("text/xml");
    System.err.println("<!-- persistence: " + MorphbankConfig.getPersistenceUnit() + " -->");
    MorphbankConfig.SYSTEM_LOGGER.info("<!-- filepath: " + filepath + " -->");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    // response.setContentType("text/html");

    try {//from w w  w  .  java2 s .c om
        // Process the uploaded items
        List<?> /* FileItem */ items = upload.parseRequest(request);
        Iterator<?> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                MorphbankConfig.SYSTEM_LOGGER.info("Form field " + item.getFieldName());
                // processFormField(item);
            } else {
                // processUploadedFile(item);
                String paramName = item.getFieldName();
                String fileName = item.getName();
                InputStream stream = item.getInputStream();
                // Reader reader = new InputStreamReader(stream);
                if ("uploadFileXml".equals(paramName)) {
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing file " + fileName);
                    processRequest(stream, out, fileName);
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing complete");
                } else {
                    // Process the input stream
                    MorphbankConfig.SYSTEM_LOGGER
                            .info("Upload field name " + item.getFieldName() + " ignored!");
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
}

From source file:admin.controller.ServletUploadFonts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  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");
    String filePath;
    String file_name = null, field_name, upload_path;
    RequestDispatcher request_dispatcher;
    String font_name = "", look_id;
    String font_family_name = "";
    PrintWriter out = response.getWriter();
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;

    try {

        // 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();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("fontname")) {
                        font_name = fi.getString();
                    }
                    if (field_name.equals("fontstylecss")) {
                        font_family_name = fi.getString();
                    }

                } else {

                    //                        check = fonts.checkAvailability(font_name);
                    //                        if (check == false){

                    field_name = fi.getFieldName();
                    file_name = fi.getName();

                    if (file_name != "") {
                        File uploadDir = new File(AppConstants.BASE_FONT_UPLOAD_PATH);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        filePath = AppConstants.BASE_FONT_UPLOAD_PATH + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                    fonts.addFont(font_name, file_name, font_family_name);
                    response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp");

                    //                            }else {
                    //                                response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp?exist=exist");
                    //                            }
                }
            }
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception while uploading fonts", e);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.MultipartHttpServletRequest.java

/**
 * Parse the multipart request. Store the info about the request parameters
 * and the uploaded files./*from  ww w .j a  v  a2 s  .  co m*/
 */
public MultipartHttpServletRequest(HttpServletRequest request, int maxFileSize) throws IOException {
    super(request);

    Map<String, List<String>> parameters = new HashMap<String, List<String>>();
    Map<String, List<FileItem>> files = new HashMap<String, List<FileItem>>();

    File tempDir = figureTemporaryDirectory(request);
    ServletFileUpload upload = createUploadHandler(maxFileSize, tempDir);

    parseQueryString(request.getQueryString(), parameters);

    try {
        List<FileItem> items = parseRequestIntoFileItems(request, upload);

        for (FileItem item : items) {
            // Process a regular form field
            if (item.isFormField()) {
                addToParameters(parameters, item.getFieldName(), item.getString("UTF-8"));
                log.debug("Form field (parameter) " + item.getFieldName() + "=" + item.getString());
            } else {
                addToFileItems(files, item);
                log.debug("File " + item.getFieldName() + ": " + item.getName());
            }
        }
    } catch (FileUploadException e) {
        fileUploadException = e;
        request.setAttribute(FileUploadServletRequest.FILE_UPLOAD_EXCEPTION, e);
    }

    this.parameters = Collections.unmodifiableMap(parameters);
    log.debug("Parameters are: " + this.parameters);
    this.files = Collections.unmodifiableMap(files);
    log.debug("Files are: " + this.files);
    request.setAttribute(FILE_ITEM_MAP, this.files);
}

From source file:it.unipmn.di.dcs.sharegrid.web.servlet.MultipartRequestWrapper.java

/** Performs initializations stuff. */
@SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type.
private void init(HttpServletRequest request, long maxSize, long maxFileSize, int thresholdSize,
        String repositoryPath) {//  w w  w.  jav a2  s  .  co  m
    if (!ServletFileUpload.isMultipartContent(request)) {
        String errorText = "Content-Type is not multipart/form-data but '" + request.getContentType() + "'";

        MultipartRequestWrapper.Log.severe(errorText);

        throw new FacesException(errorText);
    } else {
        this.params = new HashMap<String, String[]>();
        this.fileItems = new HashMap<String, FileItem>();

        DiskFileItemFactory factory = null;
        ServletFileUpload upload = null;

        //factory = new DiskFileItemFactory();
        factory = MultipartRequestWrapper.CreateDiskFileItemFactory(request.getSession().getServletContext(),
                thresholdSize, new File(repositoryPath));
        //factory.setRepository(new File(repositoryPath));
        //factory.setSizeThreshold(thresholdSize);

        upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxSize);
        upload.setFileSizeMax(maxFileSize);

        String charset = request.getCharacterEncoding();
        if (charset != null) {
            charset = ServletConstants.DefaultCharset;
        }
        upload.setHeaderEncoding(charset);

        List<FileItem> itemList = null;
        try {
            //itemList = (List<FileItem>) upload.parseRequest(request);
            itemList = (List<FileItem>) upload.parseRequest(request);
        } catch (FileUploadException fue) {
            MultipartRequestWrapper.Log.severe(fue.getMessage());
            throw new FacesException(fue);
        } catch (ClassCastException cce) {
            // This shouldn't happen!
            MultipartRequestWrapper.Log.severe(cce.getMessage());
            throw new FacesException(cce);
        }

        MultipartRequestWrapper.Log.fine("parametercount = " + itemList.size());

        for (FileItem item : itemList) {
            String key = item.getFieldName();

            //            {
            //               String value = item.getString();
            //               if (value.length() > 100) {
            //                  value = value.substring(0, 100) + " [...]";
            //               }
            //               MultipartRequestWrapper.Log.fine(
            //                  "Parameter : '" + key + "'='" + value + "' isFormField="
            //                  + item.isFormField() + " contentType='" + item.getContentType() + "'"
            //               );
            //            }
            if (item.isFormField()) {
                Object inStock = this.params.get(key);
                if (inStock == null) {
                    String[] values = null;
                    try {
                        // TODO: enable configuration of  'accept-charset'
                        values = new String[] { item.getString(ServletConstants.DefaultCharset) };
                    } catch (UnsupportedEncodingException uee) {
                        MultipartRequestWrapper.Log.warning("Caught: " + uee);

                        values = new String[] { item.getString() };
                    }
                    this.params.put(key, values);
                } else if (inStock instanceof String[]) {
                    // two or more parameters
                    String[] oldValues = (String[]) inStock;
                    String[] values = new String[oldValues.length + 1];

                    int i = 0;
                    while (i < oldValues.length) {
                        values[i] = oldValues[i];
                        i++;
                    }

                    try {
                        // TODO: enable configuration of  'accept-charset'
                        values[i] = item.getString(ServletConstants.DefaultCharset);
                    } catch (UnsupportedEncodingException uee) {
                        MultipartRequestWrapper.Log.warning("Caught: " + uee);

                        values[i] = item.getString();
                    }
                    this.params.put(key, values);
                } else {
                    MultipartRequestWrapper.Log
                            .severe("Program error. Unsupported class: " + inStock.getClass().getName());
                }
            } else {
                //String fieldName = item.getFieldName();
                //String fileName = item.getName();
                //String contentType = item.getContentType();
                //boolean isInMemory = item.isInMemory();
                //long sizeInBytes = item.getSize();
                //...
                this.fileItems.put(key, item);
            }
        }
    }
}