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:mercury.Controller.java

public void putAllRequestParametersInAttributes(HttpServletRequest request) {
    ArrayList fileBeanList = new ArrayList();
    HashMap<String, String> ht = new HashMap<String, String>();

    String fieldName = null;// ww  w.  j  a  v a2 s  . c  o m
    String fieldValue = null;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        java.util.List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                fieldName = item.getFieldName();
                fieldValue = item.getString();
                ht.put(fieldName, fieldValue);
            } else if (!item.isFormField()) {
                UploadedFileBean bean = new UploadedFileBean();
                bean.setFileItem(item);
                bean.setContentType(item.getContentType());
                bean.setFileName(item.getName());
                try {
                    bean.setInputStream(item.getInputStream());
                } catch (Exception e) {
                    System.out.println("=== Erro: " + e);
                }
                bean.setIsInMemory(item.isInMemory());
                bean.setSize(item.getSize());
                fileBeanList.add(bean);
                request.getSession().setAttribute("UPLOADED_FILE", bean);
            }
        }
    } else if (!isMultipart) {
        Enumeration<String> en = request.getParameterNames();

        String name = null;
        String value = null;
        while (en.hasMoreElements()) {
            name = en.nextElement();
            value = request.getParameter(name);
            ht.put(name, value);
        }
    }

    request.setAttribute("REQUEST_PARAMETERS", ht);
}

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

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //from  w w w  . j a va  2 s .  c  om
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            // TODO ############???##############
            upload.setHeaderEncoding("UTF-8");

            try {

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

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                // TODO ############??? ############
                filename = UUID.randomUUID().toString() + "." + extension;

                if (!ExtensionsHandler.isAllowed(resourceType, extension)) {
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                } else if (uplFile.getSize() >= MAX_FILESIZE) {
                    ur = new UploadResponse(204);
                } else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);
                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }
    }
    out.print(ur);
    out.flush();
    out.close();
    logger.debug("Exiting Connector#doPost");
}

From source file:com.stratelia.webactiv.agenda.servlets.AgendaRequestRouter.java

private File processFormUpload(AgendaSessionController agendaSc, HttpServletRequest request) {
    String logicalName = "";
    String tempFolderName = "";
    String tempFolderPath = "";
    String fileType = "";
    long fileSize = 0;
    File fileUploaded = null;/*from  w ww  .j  a  va 2s. c  om*/
    try {
        List<FileItem> items = HttpRequest.decorate(request).getFileItems();
        FileItem fileItem = FileUploadUtil.getFile(items, "fileCalendar");
        if (fileItem != null) {
            logicalName = fileItem.getName();
            if (logicalName != null) {
                logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1,
                        logicalName.length());

                // Name of temp folder: timestamp and userId
                tempFolderName = new Long(new Date().getTime()).toString() + "_" + agendaSc.getUserId();

                // Mime type of the file
                fileType = fileItem.getContentType();
                fileSize = fileItem.getSize();

                // Directory Temp for the uploaded file
                tempFolderPath = FileRepositoryManager.getAbsolutePath(agendaSc.getComponentId())
                        + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator
                        + tempFolderName;
                if (!new File(tempFolderPath).exists()) {
                    FileRepositoryManager.createAbsolutePath(agendaSc.getComponentId(),
                            GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator
                                    + tempFolderName);
                }

                // Creation of the file in the temp folder
                fileUploaded = new File(FileRepositoryManager.getAbsolutePath(agendaSc.getComponentId())
                        + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator
                        + tempFolderName + File.separator + logicalName);
                fileItem.write(fileUploaded);

                // Is a real file ?
                if (fileSize > 0) {
                    SilverTrace.debug("agenda", "AgendaRequestRouter.processFormUpload()",
                            "root.MSG_GEN_PARAM_VALUE", "fileUploaded = " + fileUploaded + " fileSize="
                                    + fileSize + " fileType=" + fileType);
                }
            }
        }
    } catch (Exception e) {
        // Other exception
        SilverTrace.warn("agenda", "AgendaRequestRouter.processFormUpload()", "root.EX_LOAD_ATTACHMENT_FAILED",
                e);
    }
    return fileUploaded;
}

From source file:com.amazonaws.serverless.proxy.internal.servlet.AwsProxyHttpServletRequest.java

private Map<String, Part> getMultipartFormParametersMap() {
    if (!ServletFileUpload.isMultipartContent(this)) { // isMultipartContent also checks the content type
        return new HashMap<>();
    }/*w w w  .java 2 s .  co  m*/

    Map<String, Part> output = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

    ServletFileUpload upload = new ServletFileUpload();
    try {
        List<FileItem> items = upload.parseRequest(this);
        for (FileItem item : items) {
            AwsProxyRequestPart newPart = new AwsProxyRequestPart(item.get());
            newPart.setName(item.getName());
            newPart.setSubmittedFileName(item.getFieldName());
            newPart.setContentType(item.getContentType());
            newPart.setSize(item.getSize());

            Iterator<String> headerNamesIterator = item.getHeaders().getHeaderNames();
            while (headerNamesIterator.hasNext()) {
                String headerName = headerNamesIterator.next();
                Iterator<String> headerValuesIterator = item.getHeaders().getHeaders(headerName);
                while (headerValuesIterator.hasNext()) {
                    newPart.addHeader(headerName, headerValuesIterator.next());
                }
            }

            output.put(item.getFieldName(), newPart);
        }
    } catch (FileUploadException e) {
        // TODO: Should we swallaw this?
        e.printStackTrace();
    }
    return output;
}

From source file:com.mingsoft.basic.servlet.UploadServlet.java

/**
 * ?post//from www . j  a va 2s .  com
 * @param req HttpServletRequest
 * @param res HttpServletResponse 
 * @throws ServletException ?
 * @throws IOException ?
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html;charset=utf-8");
    PrintWriter out = res.getWriter();
    String uploadPath = this.getServletContext().getRealPath(File.separator); // 
    String isRename = "";// ???? true:???
    String _tempPath = req.getServletContext().getRealPath(File.separator) + "temp";//
    FileUtil.createFolder(_tempPath);
    File tempPath = new File(_tempPath); // 

    int maxSize = 1000000; // ??,?? 1000000/1024=0.9M
    //String allowedFile = ".jpg,.gif,.png,.zip"; // ?
    String deniedFile = ".exe,.com,.cgi,.asp"; // ??

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    // ?????
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    // ?SizeThreshold?
    factory.setRepository(tempPath);

    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown

    try {
        List fileItems = upload.parseRequest(req);

        Iterator iter = fileItems.iterator();

        // ????
        String regExp = ".+\\\\(.+)$";

        // 
        String[] errorType = deniedFile.split(",");
        Pattern p = Pattern.compile(regExp);
        String outPath = ""; //??
        while (iter.hasNext()) {

            FileItem item = (FileItem) iter.next();
            if (item.getFieldName().equals("uploadPath")) {
                outPath += item.getString();
                uploadPath += outPath;
            } else if (item.getFieldName().equals("isRename")) {
                isRename = item.getString();
            } else if (item.getFieldName().equals("maxSize")) {
                maxSize = Integer.parseInt(item.getString()) * 1048576;
            } else if (item.getFieldName().equals("allowedFile")) {
                //               allowedFile = item.getString();
            } else if (item.getFieldName().equals("deniedFile")) {
                deniedFile = item.getString();
            } else if (!item.isFormField()) { // ???
                String name = item.getName();
                long size = item.getSize();
                if ((name == null || name.equals("")) && size == 0)
                    continue;
                try {
                    // ?? 1000000/1024=0.9M
                    upload.setSizeMax(maxSize);

                    // ?
                    // ?
                    String fileName = System.currentTimeMillis() + name.substring(name.indexOf("."));
                    String savePath = uploadPath + File.separator;
                    FileUtil.createFolder(savePath);
                    // ???
                    if (StringUtil.isBlank(isRename) || Boolean.parseBoolean(isRename)) {
                        savePath += fileName;
                        outPath += fileName;
                    } else {
                        savePath += name;
                        outPath += name;
                    }
                    item.write(new File(savePath));
                    out.print(outPath.trim());
                    logger.debug("upload file ok return path " + outPath);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    this.logger.debug(e);
                }

            }
        }
    } catch (FileUploadException e) {
        this.logger.debug(e);
    }
}

From source file:mercury.DigitalMediaDAO.java

public final Integer uploadToDigitalMedia(FileItem file) {
    Connection con = null;// ww w . j  a va2s  . c  om
    Integer serial = 0;
    String filename = file.getName();

    if (filename.lastIndexOf('\\') != -1) {
        filename = filename.substring(filename.lastIndexOf('\\') + 1);
    }

    if (filename.lastIndexOf('/') != -1) {
        filename = filename.substring(filename.lastIndexOf('/') + 1);
    }

    try {
        InputStream is = file.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        serial = getNextSerial("digital_media_id_seq");
        if (serial != 0) {
            con = getDataSource().getConnection();
            con.setAutoCommit(false);
            String sql = " INSERT INTO digital_media " + " (id, file, mime_type, file_name) "
                    + " VALUES (?, ?, ?, ?) ";
            PreparedStatement pstm = con.prepareStatement(sql);
            pstm.setInt(1, serial);
            pstm.setBinaryStream(2, bis, (int) file.getSize());
            pstm.setString(3, file.getContentType());
            pstm.setString(4, filename);
            pstm.executeUpdate();
            pstm.close();
            is.close();
            con.commit();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new DAOException(e.getMessage());
    } finally {
        closeConnection(con);
    }
    return serial;
}

From source file:com.wfms.common.web.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*  www . j  a v a  2s.  c  o m*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    //response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {

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

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                //add code
                filename = UUID.randomUUID().toString() + "." + extension;
                if (!ExtensionsHandler.isAllowed(resourceType, extension)) {
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                }
                //add conde to validate file size
                else if (uplFile.getSize() > 1024 * 1024) {
                    ur = new UploadResponse(204);
                } else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:cc.kune.core.server.manager.file.FileUploadManagerAbstract.java

@Override
@SuppressWarnings({ "rawtypes" })
protected void doPost(final HttpServletRequest req, final HttpServletResponse response)
        throws ServletException, IOException {

    beforePostStart();//w  ww  .j a  v a  2  s  .  co  m

    final DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    factory.setRepository(new File("/tmp"));

    if (!ServletFileUpload.isMultipartContent(req)) {
        LOG.warn("Not a multipart upload");
    }

    final ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown
    upload.setSizeMax(kuneProperties.getLong(KuneProperties.UPLOAD_MAX_FILE_SIZE) * 1024 * 1024);

    try {
        final List fileItems = upload.parseRequest(req);
        String userHash = null;
        StateToken stateToken = null;
        String typeId = null;
        String fileName = null;
        FileItem file = null;
        for (final Iterator iterator = fileItems.iterator(); iterator.hasNext();) {
            final FileItem item = (FileItem) iterator.next();
            if (item.isFormField()) {
                final String name = item.getFieldName();
                final String value = item.getString();
                LOG.info("name: " + name + " value: " + value);
                if (name.equals(FileConstants.HASH)) {
                    userHash = value;
                }
                if (name.equals(FileConstants.TOKEN)) {
                    stateToken = new StateToken(value);
                }
                if (name.equals(FileConstants.TYPE_ID)) {
                    typeId = value;
                }
            } else {
                fileName = item.getName();
                LOG.info("file: " + fileName + " fieldName: " + item.getFieldName() + " size: " + item.getSize()
                        + " typeId: " + typeId);
                file = item;
            }
        }
        createUploadedFile(userHash, stateToken, fileName, file, typeId);
        onSuccess(response);
    } catch (final FileUploadException e) {
        onFileUploadException(response);
    } catch (final Exception e) {
        onOtherException(response, e);
    }
}

From source file:application.controllers.admin.EmotionList.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //upload image to browser for add emotions
    //upload image to browser for add emotions
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();/*from   w w w .j av  a 2s  .co  m*/
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE);
    upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // String uploadPath = Registry.get("Host") +"/emotions-image/"+ UPLOAD_DIRECTORY;
    String uploadPath = Registry.get("imageHost") + "/emotions-image/" + UploadConstant.UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    //list image user upload
    String[] arrLinkImage = null;
    try {
        int indexImage = 0;
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        arrLinkImage = new String[formItems.size()];
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String extensionImage = "";
                for (int i = fileName.length() - 1; i >= 0; i--) {
                    if (fileName.charAt(i) == '.') {
                        break;

                    } else {
                        extensionImage = fileName.charAt(i) + extensionImage;
                    }
                }
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                String fieldName = item.getFieldName();

                // saves the file on disk
                item.write(storeFile);
                arrLinkImage[indexImage++] = item.getName();
            }
        }

    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }

    //   request.setAttribute("arrLinkImage", arrLinkImage);
    //  RequestDispatcher rd = request.getRequestDispatcher("/groupEmotion/emotion/add");
    //   rd.forward(request, response);
    //        String sessionId = request.getAttribute("sessionIdAdmin").toString();
    String sessionId = request.getSession().toString();
    String groupId = request.getParameter("groupId");
    Memcached.set("arrLinkImage-" + sessionId, 3600, arrLinkImage);

    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    response.setHeader("Location", Registry.get("Host") + "/groupEmotion/emotion/add?groupId=" + groupId);
    response.setContentType("text/html");

}

From source file:AtualizarUser.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    String caminho;/*from w  w w .  j av a2  s. c o m*/
    if (isMultipart) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = (List<FileItem>) upload.parseRequest(req);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    //                                            items.get(0).getString();
                    req.setAttribute(item.getFieldName(), item.getString());
                    resp.getWriter()
                            .println("No  campo file" + this.getServletContext().getRealPath("/img"));
                    resp.getWriter().println("Name campo: " + item.getFieldName());
                    resp.getWriter().println("Value campo: " + item.getString());

                    req.setAttribute(item.getFieldName(), item.getString());
                } else {
                    //caso seja um campo do tipo file

                    resp.getWriter().println("Campo file");
                    resp.getWriter().println("Name:" + item.getFieldName());
                    resp.getWriter().println("nome arquivo :" + item.getName());
                    resp.getWriter().println("Size:" + item.getSize());
                    resp.getWriter().println("ContentType:" + item.getContentType());
                    if (item.getName() == "" || item.getName() == null) {
                        caminho = "img\\usuario.jpg";
                    } else {
                        caminho = "img" + File.separator + new Date().getTime() + "_" + item.getName();
                        resp.getWriter().println("Caminho: " + caminho);
                        File uploadedFile = new File(
                                "E:\\Documentos\\NetBeansProjects\\SisLivros\\web\\" + caminho);
                        item.write(uploadedFile);

                    }

                    req.setAttribute("caminho", caminho);
                    req.getRequestDispatcher("AtualizarDadosUser").forward(req, resp);
                }

            }
        } catch (Exception e) {
            //            resp.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage());
        }
    }

}