Example usage for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest.

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:com.controller.UploadLogo.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww w . j  a v a 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();
                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:com.wwl.utils.Dispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In
 * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and
 * {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * /*from   www . j av  a  2 s . c om*/
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
UploadResponse doPost(final HttpServletRequest request) {
    logger.debug("Entering Dispatcher#doPost");

    Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    // check parameters  
    else if (!Command.isValidForPost(context.getCommandStr()))
        uploadResponse = UploadResponse.getInvalidCommandError();
    else if (!ResourceType.isValidType(context.getTypeStr()))
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    else if (!UtilsFile.isValidPath(context.getCurrentFolderStr()))
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    else {

        // call the Connector#fileUpload
        ResourceType type = context.getDefaultResourceType();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        try {
            List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            String fileName = FilenameUtils.getName(uplFile.getName());

            logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isNotAllowedExtension(FilenameUtils.getExtension(fileName)))
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            // Secure image check (can't be done if QuickUpload)
            else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                //fileName = UUID.randomUUID().toString()+"."+FilenameUtils.getExtension(fileName);
                fileName = new Date().getTime() + "." + FilenameUtils.getExtension(fileName);
                String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type,
                        context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName))
                    uploadResponse = UploadResponse.getOK(fileUrl);
                else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            uplFile.delete();
        } catch (InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}

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 v a 2s . 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:com.openkm.servlet.admin.MimeTypeServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    Session dbSession = null;/*w  w w.  j a  va 2s  . c o  m*/
    updateSessionManager(request);

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            MimeType mt = new MimeType();
            byte data[] = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("mt_id")) {
                        mt.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("mt_name")) {
                        mt.setName(item.getString("UTF-8").toLowerCase());
                    } else if (item.getFieldName().equals("mt_description")) {
                        mt.setDescription(item.getString("UTF-8").toLowerCase());
                    } else if (item.getFieldName().equals("mt_search")) {
                        mt.setSearch(true);
                    } else if (item.getFieldName().equals("mt_extensions")) {
                        String[] extensions = item.getString("UTF-8").split(" ");

                        for (int i = 0; i < extensions.length; i++) {
                            mt.getExtensions().add(extensions[i].toLowerCase());
                        }
                    }
                } else {
                    is = item.getInputStream();
                    data = IOUtils.toByteArray(is);
                    mt.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    is.close();
                }
            }

            if (action.equals("create")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                long id = MimeTypeDAO.create(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_CREATE", Long.toString(id), null, mt.toString());
                list(userId, request, response);
            } else if (action.equals("edit")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                MimeTypeDAO.update(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_EDIT", Long.toString(mt.getId()), null,
                        mt.toString());
                list(userId, request, response);
            } else if (action.equals("delete")) {
                MimeTypeDAO.delete(mt.getId());
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_DELETE", Long.toString(mt.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importMimeTypes(userId, request, response, data, dbSession);
                list(userId, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        HibernateUtil.close(dbSession);
    }
}

From source file:net.fckeditor.connector.MyDispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In
 * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and
 * {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * // w ww. j a  v a  2 s  .  c  o  m
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
UploadResponse doPost(final HttpServletRequest request) {
    logger.debug("Entering Dispatcher#doPost");

    Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request))
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    // check parameters  
    else if (!Command.isValidForPost(context.getCommandStr()))
        uploadResponse = UploadResponse.getInvalidCommandError();
    else if (!ResourceType.isValidType(context.getTypeStr()))
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    else if (!UtilsFile.isValidPath(context.getCurrentFolderStr()))
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    else {

        // call the Connector#fileUpload
        ResourceType type = context.getDefaultResourceType();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        try {
            List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            String fileName = FilenameUtils.getName(uplFile.getName());
            fileName = UUID.randomUUID().toString().replace("-", "") + "."
                    + FilenameUtils.getExtension(fileName);
            logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isDeniedExtension(FilenameUtils.getExtension(fileName)))
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            // Secure image check (can't be done if QuickUpload)
            else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type,
                        context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName))
                    uploadResponse = UploadResponse.getOK(fileUrl);
                else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            uplFile.delete();
        } catch (InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}

From source file:admin.controller.ServletAddLooks.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w w.  j a va 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
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    super.processRequest(request, response);
    String filePath;
    String fileName, fieldName;
    Looks look;
    RequestDispatcher request_dispatcher;
    String look_name = null;
    Integer organization_id = 0;
    boolean check;
    look = new Looks();
    check = false;

    response.setContentType("text/html;charset=UTF-8");
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        String uploadPath = AppConstants.LOOK_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();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();

                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    try {
                        if (fieldName.equals("lookname")) {
                            look_name = fi.getString();
                        }
                        if (fieldName.equals("organization")) {
                            organization_id = Integer.parseInt(fi.getString());
                        }
                    } catch (Exception e) {
                        logger.log(Level.SEVERE, "Exception while getting the look_name and organization_id",
                                e);
                    }
                } else {
                    check = look.checkAvailability(look_name, organization_id);

                    if (check == false) {
                        fieldName = fi.getFieldName();
                        fileName = fi.getName();

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

                        //                            int inStr = fileName.indexOf(".");
                        //                            String Str = fileName.substring(0, inStr);
                        //
                        //                            fileName = look_name + "_" + Str + ".png";
                        fileName = look_name + "_" + fileName;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

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

                        fi.write(storeFile);

                        look.addLooks(look_name, fileName, organization_id);
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
                    } else {
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp?exist=exist");
                    }

                }
            }

        } else {
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while uploading the Looks image", ex);
    }
}

From source file:com.krawler.br.spring.RConverterImpl.java

public Map convertWithFile(HttpServletRequest request, Map reqParams) throws ProcessException {
    HashMap itemMap = new HashMap(), tmpMap = new HashMap();
    try {//from w  ww  .  j  a va2 s .c om
        FileItemFactory factory = new DiskFileItemFactory(4096, new File("/tmp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1000000);
        List fileItems = upload.parseRequest(request);
        Iterator iter = fileItems.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            String key = item.getFieldName();
            OperationParameter o = (OperationParameter) reqParams.get(key);
            if (reqParams.containsKey(key)) {
                if (item.isFormField()) {
                    putItem(tmpMap, key,
                            getValue(item.getString("UTF-8"), mb.getModuleDefinition(o.getType())));
                } else {
                    File destDir = new File(StorageHandler.GetProfileImgStorePath());
                    if (!destDir.exists()) {
                        destDir.mkdirs();
                    }

                    File f = new File(destDir, UUID.randomUUID() + "_" + item.getName());
                    try {
                        item.write(f);
                    } catch (Exception ex) {
                        Logger.getLogger(RConverterImpl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    putItem(tmpMap, key, f.getAbsolutePath());
                }
            }
        }

        iter = tmpMap.keySet().iterator();

        while (iter.hasNext()) {
            String key = (String) iter.next();
            OperationParameter o = (OperationParameter) reqParams.get(key);
            itemMap.put(key, convertToMultiType((List) tmpMap.get(key), o.getMulti(), o.getType()));
        }

    } catch (FileUploadException ex) {
        throw new ProcessException(ex.getMessage(), ex);
    } catch (UnsupportedEncodingException e) {
        throw new ProcessException(e.getMessage(), e);
    }
    return itemMap;
}

From source file:calliope.handler.post.AeseImportHandler.java

/**
 * Parse the import params from the request
 * @param request the http request//www .  java2s.c  o m
 */
void parseImportParams(HttpServletRequest request) throws AeseException {
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString();
                    if (fieldName.equals(Params.DOCID)) {
                        if (contents.startsWith("/")) {
                            contents = contents.substring(1);
                            int pos = contents.indexOf("/");
                            if (pos != -1) {
                                database = contents.substring(0, pos);
                                contents = contents.substring(pos + 1);
                            }
                        }
                        docID = new DocID(contents);
                    } else if (fieldName.startsWith(Params.SHORT_VERSION))
                        nameMap.put(fieldName.substring(Params.SHORT_VERSION.length()), item.getString());
                    else if (fieldName.equals(Params.LC_STYLE) || fieldName.equals(Params.STYLE)) {
                        jsonKeys.put(fieldName.toLowerCase(), contents);
                        style = contents;
                    } else if (fieldName.equals(Params.DEMO)) {
                        if (contents != null && contents.equals("brillig"))
                            demo = false;
                        else
                            demo = true;
                    } else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.FILTER))
                        filterName = contents.toLowerCase();
                    else if (fieldName.equals(Params.SIMILARITY))
                        similarityTest = contents != null && contents.equals("1");
                    else if (fieldName.equals(Params.SPLITTER))
                        splitterName = contents;
                    else if (fieldName.equals(Params.STRIPPER))
                        stripperName = contents;
                    else if (fieldName.equals(Params.TEXT))
                        textName = contents.toLowerCase();
                    else if (fieldName.equals(Params.XSLT))
                        xslt = getConfig(Config.xslt, contents);
                    else if (fieldName.equals(Params.DICT))
                        dict = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.HH_EXCEPTIONS))
                        hhExceptions = contents;
                    else
                        jsonKeys.put(fieldName, contents);
                }
            } else if (item.getName().length() > 0) {
                try {
                    // assuming that the contents are text
                    //item.getName retrieves the ORIGINAL file name
                    String type = item.getContentType();
                    if (type != null && type.startsWith("image/")) {
                        InputStream is = item.getInputStream();
                        ByteHolder bh = new ByteHolder();
                        while (is.available() > 0) {
                            byte[] b = new byte[is.available()];
                            is.read(b);
                            bh.append(b);
                        }
                        ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData());
                        images.add(iFile);
                    } else {
                        byte[] rawData = item.get();
                        guessEncoding(rawData);
                        //System.out.println(encoding);
                        File f = new File(item.getName(), new String(rawData, encoding));
                        files.add(f);
                    }
                } catch (Exception e) {
                    throw new AeseException(e);
                }
            }
        }
        if (style == null)
            style = DEFAULT_STYLE;
    } catch (Exception e) {
        throw new AeseException(e);
    }
    //        System.out.println("Import params received:");
    //        System.out.println("docID="+docID.get());
    //        System.out.println("style="+style);
    //        System.out.println("filterName="+filterName);
    //        System.out.println("database="+database);
    //        System.out.println("splitterName="+splitterName);
    //        System.out.println("stripperName="+stripperName);
    //        System.out.println("encoding="+encoding);
    //        System.out.println("hhExceptions="+hhExceptions);
    //        System.out.println("similarityTest="+similarityTest);
    //        System.out.println("dict="+dict);
    //        System.out.println("xslt="+xslt);
    //        System.out.println("demo="+demo);
    //        System.out.println("textName="+textName);
}

From source file:com.skin.generator.action.UploadTestAction.java

/**
 * @param request//from  w  w  w . ja  v  a  2  s.c  om
 * @return Map<String, Object>
 * @throws Exception
 */
public Map<String, Object> parse(HttpServletRequest request) throws Exception {
    String repository = System.getProperty("java.io.tmpdir");
    int maxFileSize = 1024 * 1024 * 1024;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(new File(repository));
    factory.setSizeThreshold(1024 * 1024);
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
    servletFileUpload.setFileSizeMax(maxFileSize);
    servletFileUpload.setSizeMax(maxFileSize);
    Map<String, Object> map = new HashMap<String, Object>();
    List<?> list = servletFileUpload.parseRequest(request);

    if (list != null && list.size() > 0) {
        for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
            FileItem item = (FileItem) iterator.next();

            if (item.isFormField()) {
                logger.debug("form field: {}, {}", item.getFieldName(), item.toString());
                map.put(item.getFieldName(), item.getString("utf-8"));
            } else {
                logger.debug("file field: {}", item.getFieldName());
                map.put(item.getFieldName(), item);
            }
        }
    }
    return map;
}

From source file:com.intranet.intr.proveedores.ProvController.java

@RequestMapping(value = "updateArchivos.htm", method = RequestMethod.POST)
public String updateArchivos_post(@ModelAttribute("provPresupAdj") prov_presup_adj provPresupAdj,
        BindingResult result, HttpServletRequest request) {
    String mensaje = "";

    try {/*  w ww. j av a 2 s.c om*/

        String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\archivosProveedores";
        //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
        //String ubicacionArchivo="C:\\";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024);
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> partes = upload.parseRequest(request);

        for (FileItem item : partes) {
            System.out.println("NOMBRE FOTO: " + item.getContentType());
            File file = new File(ubicacionArchivo, item.getName());

            item.write(file);
            prov_presup_adj pp = new prov_presup_adj();
            pp.setId_prov_presup(idPr);
            pp.setNombre(item.getName());
            pp.setTipo(item.getContentType());
            provPresupAdjService.Insert(pp);
        }
        //c.setImagenes(arc);

    } catch (Exception ex) {

    }
    return "redirect:updatePresupProv.htm?idP=" + idPr;

}