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:edu.xtec.colex.client.beans.ColexRecordBean.java

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

    Vector vAttachments = new Vector();

    getStructure();

    Record r = new Record();
    Field fAux;
    String paramName;
    String fieldType;
    String fieldName;
    String fieldId;

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

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

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

                if (fi.getSize() != 0) //case there is no attachment
                {
                    sNomFitxer = Utils.getFileName(fi.getName());

                    fi.setFieldName(fieldName);

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

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

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

            String sDay = pmRequest.getParameter("fdDD_" + fieldId);
            String sMonth = pmRequest.getParameter("fdMM_" + fieldId);
            String sYear = pmRequest.getParameter("fdYYYY_" + fieldId);

            fAux.setName(fieldName);
            fAux.setValue(sYear + "-" + sMonth + "-" + sDay);
            r.addField(fAux);
        }
    }
    addRecord(r, vAttachments);
}

From source file:com.silverpeas.classifieds.control.ClassifiedsSessionController.java

/**
 * update classified image /*w  ww .ja  va2 s.co  m*/
 * @param fileImage : FileItem
 * @param imageId : String
 * @param classifiedId : String
 */
public void updateClassifiedImage(FileItem fileImage, String imageId, String classifiedId) {
    SimpleDocument classifiedImage = null;
    try {
        SimpleDocumentPK sdPK = new SimpleDocumentPK(imageId, getComponentId());
        classifiedImage = AttachmentServiceFactory.getAttachmentService().searchDocumentById(sdPK, null);
    } catch (Exception e) {
        throw new ClassifiedsRuntimeException("ClassifiedsSessionController.updateClassifiedImage()",
                SilverpeasRuntimeException.ERROR, "classifieds.MSG_ERR_GET_IMAGE", e);
    }

    if (classifiedImage != null) {
        Date updateDate = new Date();
        String fileName = FileUtil.getFilename(fileImage.getName());
        long size = fileImage.getSize();
        String mimeType = FileUtil.getMimeType(fileName);

        classifiedImage.setDocumentType(DocumentType.attachment);
        classifiedImage.setFilename(fileName);
        classifiedImage.setLanguage(null);
        classifiedImage.setTitle("");
        classifiedImage.setDescription("");
        classifiedImage.setSize(size);
        classifiedImage.setContentType(mimeType);
        classifiedImage.setUpdatedBy(getUserId());
        classifiedImage.setUpdated(updateDate);

        try {
            AttachmentServiceFactory.getAttachmentService().updateAttachment(classifiedImage,
                    fileImage.getInputStream(), true, false);
        } catch (Exception e) {
            throw new ClassifiedsRuntimeException("ClassifiedsSessionController.updateClassifiedImage()",
                    SilverpeasRuntimeException.ERROR, "classifieds.MSG_CLASSIFIED_IMAGE_NOT_UPDATE", e);
        }

    } else {
        createClassifiedImage(fileImage, classifiedId);
    }
}

From source file:egovframework.asadal.asapro.com.cmm.web.AsaproEgovMultipartResolver.java

/**
 * multipart?  parsing? ./*  w w  w . jav a 2  s .  com*/
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {

    //? 3.0  
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    // Extract multipart files and multipart parameters.
    for (Iterator it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);

                //? 3.0 ? API? 
                List<MultipartFile> fileList = new ArrayList<MultipartFile>();
                fileList.add(file);

                if (!AsaproEgovWebUtil.checkAllowUploadFileExt(file.getOriginalFilename()))
                    throw new MultipartException(" ? ? .");

                if (multipartFiles.put(fileItem.getName(), fileList) != null) { // CHANGED!!
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                            + file.getStorageDescription());
                }
            }

        }
    }

    return new MultipartParsingResult(multipartFiles, multipartParameters, null);
}

From source file:egovframework.oe1.cms.com.web.EgovOe1MultipartResolver.java

/**
 * multipart?  parsing? ./*w ww.  java2  s. c  o  m*/
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {
    Map multipartFiles = new HashMap();
    Map multipartParameters = new HashMap();

    // Extract multipart files and multipart parameters.
    for (Iterator it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
                if (multipartFiles.put(fileItem.getName(), file) != null) { // CHANGED!!
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                            + file.getStorageDescription());
                }
            }

        }
    }

    return new MultipartParsingResult((MultiValueMap<String, MultipartFile>) multipartFiles,
            (Map<String, String[]>) multipartParameters);
}

From source file:lcn.module.oltp.web.common.base.MultipartResolver.java

/**
 * multipart?  parsing? ./*from   www  . j a  v a2 s  .  c  o  m*/
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {

    //? 3.0  
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    //   Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    //   Map multipartFiles = new HashMap();
    Map multipartParameters = new HashMap();

    // Extract multipart files and multipart parameters.
    for (Iterator it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);

                //? 3.0 ? API? 
                List<MultipartFile> fileList = new ArrayList<MultipartFile>();
                fileList.add(file);

                if (multipartFiles.put(fileItem.getName(), fileList) != null) { // CHANGED!!
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                            + file.getStorageDescription());
                }
            }

        }
    }
    return new MultipartParsingResult((MultiValueMap<String, MultipartFile>) multipartFiles,
            (Map<String, String[]>) multipartParameters, multipartParameters);

    //   return new MultipartParsingResult(multipartFiles, multipartParameters);
}

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

/**
 * This method manages the user input fields managing two cases 
 * distinguished by the type of the input <form ... statement
 * The use of upload file controls needs the use of "multipart/form-data"
 * while the else condition of the isMultipartContent check manages the 
 * standard input case. The multipart content needs a manual processing of
 * all <form items/*  w  w  w .  ja v  a2s.c o m*/
 * All form' input items are identified by the 'name' input property
 * inside the jsp file
 * 
 * @param request   ActionRequest instance (processAction)
 * @param appInput  AppInput instance storing the jobSubmission data
 */
void getInputForm(ActionRequest request, AppInput appInput) {
    if (PortletFileUpload.isMultipartContent(request))
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {
                case file_inputFile:
                    appInput.inputFileName = item.getString();
                    processInputFile(item, appInput);
                    break;
                case inputFile:
                    appInput.inputFileText = item.getString();
                    break;
                case JobIdentifier:
                    appInput.jobIdentifier = item.getString();
                    break;
                default:
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName                                                   
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        appInput.inputFileName = (String) request.getParameter("file_inputFile");
        appInput.inputFileText = (String) request.getParameter("inputFile");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");
    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "inputFileName: '"
            + appInput.inputFileName + "'" + LS + "inputFileText: '" + appInput.inputFileText + "'" + LS
            + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS);
}

From source file:forseti.JGestionArchivos.java

public void SubirArchivo(HttpServletRequest request) throws ServletException {
    try {/*from  ww w.j a  v a 2  s. com*/
        FileItem actual = (FileItem) m_Archivos.elementAt(0);

        //Ahora agrega el archivo al mensaje
        String charset = "UTF-8";
        String requestURL = "https://" + m_URL + "/servlet/SAFAwsS3Conn";

        MultipartUtility multipart = new MultipartUtility(requestURL, charset);

        multipart.addHeaderField("User-Agent", "CodeJava");
        multipart.addHeaderField("Test-Header", "Header-Value");

        multipart.addFormField("SERVER", m_HOST);
        multipart.addFormField("DATABASE", JUtil.getSesion(request).getBDCompania());
        multipart.addFormField("USER", m_S3_USERNAME);
        multipart.addFormField("PASSWORD", m_S3_PASSWORD);
        multipart.addFormField("ACTION", "SUBIR");
        multipart.addFormField("ID_MODULO", m_ID_MODULO);
        multipart.addFormField("OBJIDS", m_OBJIDS);
        multipart.addFormField("IDSEP", m_IDSEP);
        multipart.addFormField("NOMBRE", actual.getName());
        multipart.addFormField("TAMBITES", Long.toString(actual.getSize()));

        JProcessSet setPer = new JProcessSet(null);
        String sql = "select coalesce(sum(tambites),0) as totbites from tbl_s3_registros_exitosos where servidor = '"
                + JUtil.p(m_HOST) + "' and bd = '" + JUtil.getSesion(request).getBDCompania() + "'";
        //System.out.println(sql);
        setPer.ConCat(true);
        setPer.setSQL(sql);
        setPer.Open();

        multipart.addFormField("TOTBITES", setPer.getAbsRow(0).getSTS("Col1"));

        multipart.addFilePart("fileUpload", actual);
        InputStream response = multipart.connect();

        // Recibe la respuesta del servidor, esta debe estar en formato xml
        SAXBuilder builder = new SAXBuilder();
        Document document = (Document) builder.build(response);
        Element S3 = document.getRootElement();

        if (S3.getName().equals("S3")) {
            String SQL = "SELECT * FROM sp_s3_registros_exitosos('" + JUtil.q(m_HOST) + "','"
                    + JUtil.q(JUtil.getSesion(request).getBDCompania()) + "','" + JUtil.q(m_ID_MODULO) + "','"
                    + JUtil.q(m_OBJIDS) + "','" + JUtil.q(m_IDSEP) + "','" + JUtil.q(actual.getName()) + "',"
                    + Long.toString(actual.getSize()) + ") as (RES integer);";
            Connection con = JAccesoBD.getConexion();
            Statement s = con.createStatement();
            ResultSet rs = s.executeQuery(SQL);
            if (rs.next()) {
                int res = rs.getInt("RES");
                System.out.println("Resultado del archivo S3 en Cliente: " + res);
            }
            s.close();
            JAccesoBD.liberarConexion(con);

            m_StatusS3 = OKYDOKY;
        } else if (S3.getName().equals("SIGN_ERROR"))// Significan errores
        {
            m_StatusS3 = ERROR;
            m_Error += "Codigo de Error JAwsS3Conn: " + S3.getAttribute("CodError") + "<br>"
                    + S3.getAttribute("MsjError");
        } else {
            m_StatusS3 = ERROR;
            m_Error += "ERROR: El archivo recibido es un archivo XML, pero no parece ser una respuesta de archivo ni una respuesta de ERROR del servidor JAwsS3Conn. Esto debe ser investigado de inmediato, Contacta con tu intermediario de archivos AWS S3 Forseti para que te explique el problema";
        }

        multipart.disconnect();
        // Fin de archivo grabado
        ///////////////////////////////////////////////////////////////////////////
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        m_StatusS3 = ERROR;
        m_Error = "Error de archivos S3: " + e1.getMessage();
    } catch (IOException e1) {
        e1.printStackTrace();
        m_StatusS3 = ERROR;
        m_Error = "Error de Entrada/Salida S3: " + e1.getMessage();
    } catch (JDOMException e1) {
        e1.printStackTrace();
        m_StatusS3 = ERROR;
        m_Error = "Error de JDOMException S3: " + e1.getMessage();
    } catch (SQLException e1) {
        e1.printStackTrace();
        m_StatusS3 = ERROR;
        m_Error = "Error de SQLException S3: " + e1.getMessage();
    }
}

From source file:com.uniquesoft.uidl.servlet.UploadServlet.java

/**
 * This method parses the submit action, puts in session a listener where the
 * progress status is updated, and eventually stores the received data in
 * the user session./* ww  w  .  j  a v  a  2s.c o  m*/
 * 
 * returns null in the case of success or a string with the error
 * 
 */
@SuppressWarnings("unchecked")
protected String parsePostRequest(HttpServletRequest request, HttpServletResponse response) {

    try {
        String delay = request.getParameter(PARAM_DELAY);
        uploadDelay = Integer.parseInt(delay);
    } catch (Exception e) {
    }

    HttpSession session = request.getSession();

    logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received.");

    AbstractUploadListener listener = getCurrentListener(request);
    if (listener != null) {
        if (listener.isFrozen() || listener.isCanceled() || listener.getPercent() >= 100) {
            removeCurrentListener(request);
        } else {
            String error = getMessage("busy");
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") " + error);
            return error;
        }
    }
    // Create a file upload progress listener, and put it in the user session,
    // so the browser can use ajax to query status of the upload process
    listener = createNewListener(request);

    List<FileItem> uploadedItems;
    try {

        // Call to a method which the user can override
        checkRequest(request);

        // Create the factory used for uploading files,
        FileItemFactory factory = getFileItemFactory(getContentLength(request));
        ServletFileUpload uploader = new ServletFileUpload(factory);
        uploader.setSizeMax(maxSize);
        uploader.setProgressListener(listener);

        // Receive the files
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsing HTTP POST request ");
        uploadedItems = uploader.parseRequest(request);
        session.removeAttribute(getSessionLastFilesKey(request));
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsed request, " + uploadedItems.size()
                + " items received.");

        // Received files are put in session
        List<FileItem> sessionFiles = getMySessionFileItems(request);
        if (sessionFiles == null) {
            sessionFiles = new ArrayList<FileItem>();
        }

        String error = "";

        if (uploadedItems.size() > 0) {

            // We append to the field name the sequence of the uploaded file
            int cnt = 0;
            for (FileItem i : uploadedItems) {
                if (!i.isFormField()) {
                    i.setFieldName(i.getFieldName().replace(UConsts.MULTI_SUFFIX, "") + "-" + cnt++);
                }
            }

            sessionFiles.addAll(uploadedItems);
            String msg = "";
            for (FileItem i : sessionFiles) {
                msg += i.getFieldName() + " => " + i.getName() + "(" + i.getSize() + " bytes),";
            }
            logger.debug("UPLOAD-SERVLET (" + session.getId() + ") puting items in session: " + msg);
            session.setAttribute(getSessionFilesKey(request), sessionFiles);
            session.setAttribute(getSessionLastFilesKey(request), uploadedItems);
        } else {
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") error NO DATA received ");
            error += getMessage("no_data");
        }

        return error.length() > 0 ? error : null;

        // So much silly questions in the list about this issue.  
    } catch (LinkageError e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Exception: " + e.getMessage() + "\n"
                + stackTraceToString(e));
        RuntimeException ex = new UploadActionException(getMessage("restricted", e.getMessage()), e);
        listener.setException(ex);
        throw ex;
    } catch (SizeLimitExceededException e) {
        RuntimeException ex = new UploadSizeLimitException(e.getPermittedSize(), e.getActualSize());
        listener.setException(ex);
        throw ex;
    } catch (UploadSizeLimitException e) {
        listener.setException(e);
        throw e;
    } catch (UploadCanceledException e) {
        listener.setException(e);
        throw e;
    } catch (UploadTimeoutException e) {
        listener.setException(e);
        throw e;
    } catch (Throwable e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Unexpected Exception -> "
                + e.getMessage() + "\n" + stackTraceToString(e));
        e.printStackTrace();
        RuntimeException ex = new UploadException(e);
        listener.setException(ex);
        throw ex;
    }
}

From source file:com.enonic.vertical.userservices.AbstractUserServicesHandlerController.java

private ExtendedMap parseMultiPartRequest(HttpServletRequest request) {
    ExtendedMap formItems = new ExtendedMap(true);
    try {/*w  ww.j  a  v  a2 s .c  om*/
        List paramList = fileUpload.parseRequest(request);
        for (Iterator iter = paramList.iterator(); iter.hasNext();) {
            FileItem fileItem = (FileItem) iter.next();

            String name = fileItem.getFieldName();

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

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

    return formItems;
}

From source file:fr.paris.lutece.plugins.crm.modules.form.service.draft.CRMDraftBackupService.java

/**
 * Stores all file for the subform to BlobStore and replaces
 * {@link FileItem} by {@link BlobStoreFileItem}
 * @param mapResponses the map of <id_entry,Responses>
 * @param session the session//w w w  .ja va  2 s.  c o m
 */
private void storeFiles(Map<Integer, List<Response>> mapResponses, HttpSession session) {
    for (Entry<Integer, List<Response>> entryMap : mapResponses.entrySet()) {
        int nIdEntry = entryMap.getKey();
        String strIdEntry = Integer.toString(nIdEntry);
        List<FileItem> uploadedFiles = FormAsynchronousUploadHandler.getHandler()
                .getListUploadedFiles(IEntryTypeService.PREFIX_ATTRIBUTE + strIdEntry, session);

        if (uploadedFiles != null) {
            List<FileItem> listBlobStoreFileItems = new ArrayList<FileItem>();

            for (int nIndex = 0; nIndex < uploadedFiles.size(); nIndex++) {
                FileItem fileItem = uploadedFiles.get(nIndex);
                String strFileName = fileItem.getName();

                if (!(fileItem instanceof BlobStoreFileItem)) {
                    // file is not blobstored yet
                    String strFileBlobId;
                    InputStream is = null;

                    try {
                        is = fileItem.getInputStream();
                        strFileBlobId = _blobStoreService.storeInputStream(is);
                    } catch (IOException e1) {
                        IOUtils.closeQuietly(is);
                        _logger.error(e1.getMessage(), e1);
                        throw new AppException(e1.getMessage(), e1);
                    }

                    String strJSON = BlobStoreFileItem.buildFileMetadata(strFileName, fileItem.getSize(),
                            strFileBlobId, fileItem.getContentType());

                    if (_logger.isDebugEnabled()) {
                        _logger.debug("Storing " + fileItem.getName() + " with : " + strJSON);
                    }

                    String strFileMetadataBlobId = _blobStoreService.store(strJSON.getBytes());

                    try {
                        BlobStoreFileItem blobStoreFileItem = new BlobStoreFileItem(strFileMetadataBlobId,
                                _blobStoreService);
                        listBlobStoreFileItems.add(blobStoreFileItem);
                    } catch (NoSuchBlobException nsbe) {
                        // nothing to do, blob is deleted and draft is not up to date.
                        if (_logger.isDebugEnabled()) {
                            _logger.debug(nsbe.getMessage());
                        }
                    } catch (Exception e) {
                        _logger.error("Unable to create new BlobStoreFileItem " + e.getMessage(), e);
                        throw new AppException(e.getMessage(), e);
                    }
                } else {
                    // nothing to do
                    listBlobStoreFileItems.add(fileItem);
                }
            }

            // replace current file list with the new one
            uploadedFiles.clear();
            uploadedFiles.addAll(listBlobStoreFileItems);
        }
    }
}