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

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

Introduction

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

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

Usage

From source file:edu.harvard.hul.ois.drs.pdfaconvert.service.servlets.PdfaConverterServlet.java

/**
 * Handles the file upload for PdfaConverter processing via streaming of the file
 * using the <code>POST</code> method. Example: curl -X POST -F datafile=@
 * <path/to/file> <host>:[<port>]/pdfa-converter/examine Note: "pdfa-converter" in the above URL
 * needs to be adjusted to the final name of the WAR file.
 *
 * @param request/*  w  w  w .  j  a v a  2  s .  c o  m*/
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.info("Entering doPost()");
    if (!ServletFileUpload.isMultipartContent(request)) {
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                " Missing Multipart Form Data. ", request.getRequestURL().toString());
        sendErrorMessageResponse(errorMessage, response);
        return;
    }

    try {
        List<FileItem> formItems = upload.parseRequest(request);
        Iterator<FileItem> iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = iter.next();

            // processes only fields that are not form fields
            // if (!item.isFormField()) {
            if (!item.isFormField() && item.getFieldName().equals(FORM_FIELD_DATAFILE)) {

                long fileSize = item.getSize();
                if (fileSize < 1) {
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                            " Missing File Data. ", request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                }
                // save original uploaded file name
                InputStream inputStream = item.getInputStream();
                String origFileName = item.getName();

                DiskFileItemExt itemExt = new DiskFileItemExt(item.getFieldName(), item.getContentType(),
                        item.isFormField(), item.getName(), (maxInMemoryFileSizeMb * (int) MB_MULTIPLIER),
                        factory.getRepository());
                // Create a temporary unique filename for a file containing the original temp filename plus the real filename containing its file type suffix.
                String tempFilename = itemExt.getTempFile().getName();
                StringBuilder realFileTypeFilename = new StringBuilder(tempFilename);
                realFileTypeFilename.append('-');
                realFileTypeFilename.append(origFileName);
                // create the file in the same temporary directory
                File realInputFile = new File(factory.getRepository(), realFileTypeFilename.toString());

                // strip out suffix before saving to ServletRequestListener
                request.setAttribute(TEMP_FILE_NAME_KEY, tempFilename.substring(0, tempFilename.indexOf('.')));

                // turn InputStream into a File in temp directory
                OutputStream outputStream = new FileOutputStream(realInputFile);
                IOUtils.copy(inputStream, outputStream);
                outputStream.close();

                try {
                    // Send it to the PdfaConverter processor...
                    sendPdfaConverterExamineResponse(realInputFile, origFileName, request, response);
                } finally {
                    // delete both original temporary file -- if large enough will have been persisted to disk -- and our created file
                    if (!item.isInMemory()) { // 
                        item.delete();
                    }
                    if (realInputFile.exists()) {
                        realInputFile.delete();
                    }
                }

            } else {
                ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                        " The request did not have the correct name attribute of \"datafile\" in the form processing. ",
                        request.getRequestURL().toString(), " Processing halted.");
                sendErrorMessageResponse(errorMessage, response);
                return;
            }

        }

    } catch (FileUploadException ex) {
        logger.error(ex);
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                " There was an unexpected server error: " + ex.getMessage(), request.getRequestURL().toString(),
                " Processing halted.");
        sendErrorMessageResponse(errorMessage, response);
        return;
    }
}

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

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

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

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

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

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

From source file:com.fujitsu.gwt.bewebapp.server.GWTUploadServlet.java

/**
 * Override executeAction to save the received files in a custom place and
 * delete this items from session./*  w ww  .  j  a v a 2  s  .co m*/
 */
@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {

    String response = "";
    int cont = 0;

    String displayName = "";
    String originalName = "";
    String fileExtension = "bin";
    String comments = "";
    String pageId = "";
    String atype = "";
    String newversion = "";
    String existingaid = "";
    String visibility = "";
    File tempFile = null;
    for (FileItem item : sessionFiles) {

        if (false == item.isFormField()) {
            cont++;
            try {

                String fName = item.getName();
                fName = fName.replace('\\', '/');
                int indx = fName.lastIndexOf("/");
                if (indx > 0) {
                    originalName = fName.substring(indx + 1);
                } else {
                    originalName = fName;
                }

                int dotPos = originalName.lastIndexOf(".");
                if (dotPos > 0) {
                    fileExtension = originalName.substring(dotPos + 1);
                }

                String tmpFileName = "upload-" + rd.nextInt();
                // Create a temporary file placed in the default system temp
                // folder
                tempFile = File.createTempFile(tmpFileName, ".bin");
                item.write(tempFile);

                // / Save a list with the received files
                receivedFiles.put(item.getFieldName(), tempFile);
                receivedContentTypes.put(item.getFieldName(), item.getContentType());

                // / Send a customized message to the client.
                response += "Successfully attached the file " + item.getName();

            } catch (Exception e) {
                throw new UploadActionException(e.getMessage());
            }
        } else {
            if ("aname".equals(item.getFieldName())) {
                displayName = item.getString();
            } else if ("desc".equals(item.getFieldName())) {
                comments = item.getString();
            } else if ("pageid".equals(item.getFieldName())) {
                pageId = item.getString();
            } else if ("atype".equals(item.getFieldName())) {
                atype = item.getString();
            } else if ("newversion".equals(item.getFieldName())) {
                newversion = item.getString();
            } else if ("existingaid".equals(item.getFieldName())) {
                existingaid = item.getString();
            } else if ("visibility".equals(item.getFieldName())) {
                visibility = item.getString();
            } else {
                System.out.println("Unknows FiledName:" + item.getFieldName() + "=" + item.getString());
            }
        }

        if (displayName.length() == 0) {
            displayName = originalName;
        } else if (!displayName.endsWith("." + fileExtension)) {
            displayName = displayName + "." + fileExtension;
        }
    }
    try {

        String userKey = (String) request.getSession().getAttribute("userKey");
        UserProfile user = null;
        if (userKey != null) {
            user = UserManager.getUserProfileByKey(userKey);

        } else {
            throw new NGException("nugen.exception.user.must.be.login", null);
        }
        AuthDummy ar = new AuthDummy(user, new StringWriter());
        ar.req = request;
        NGPage ngp = (NGPage) NGPageIndex.getContainerByKeyOrFail(pageId);
        AttachmentRecord attachment = null;

        if (existingaid != null) {
            if ((!existingaid.equals("0") && (existingaid.length() > 0))) {
                attachment = ngp.findAttachmentByIDOrFail(existingaid);
            }
        }

        if (attachment == null) {
            //see if there exists an attachment with that name, and use that
            attachment = ngp.findAttachmentByName(displayName);
        }
        if (attachment == null) {
            //last resort, actually create one
            attachment = ngp.createAttachment();
            attachment.setType("FILE");
        }

        attachment.setDisplayName(displayName);
        attachment.setComment(comments);
        attachment.setModifiedBy(ar.getBestUserId());
        attachment.setModifiedDate(ar.nowTime);
        if (atype.equals("Public")) {
            attachment.setVisibility(1);
        } else {
            attachment.setVisibility(2);
        }

        FileInputStream contentStream = new FileInputStream(tempFile);
        AttachmentVersion av = attachment.streamNewVersion(ar, ngp, contentStream);

        HistoryRecord.createHistoryRecord(ngp, attachment.getId(), HistoryRecord.CONTEXT_TYPE_DOCUMENT,
                ar.nowTime, HistoryRecord.EVENT_DOC_ADDED, ar, "");

        ngp.saveContent(ar, "Modified attachments");
    } catch (Exception e) {
        e.printStackTrace();
        throw new UploadActionException(e.getMessage());
    } finally {
        NGPageIndex.clearLocksHeldByThisThread();
    }

    // / Remove files from session because we have a copy of them
    removeSessionFileItems(request);

    // / Send your customized message to the client.
    return response;
}

From source file:it.lufraproini.cms.servlet.upload_user_img.java

private Map prendiInfoFile(HttpServletRequest request) throws ErroreGrave, IOException {
    Map infofile = new HashMap();
    //riutilizzo codice prof. Della Penna per l'upload
    if (ServletFileUpload.isMultipartContent(request)) {
        // Funzioni delle librerie Apache per l'upload
        try {/*ww  w .j a v a  2  s.  c  o m*/
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items;
            FileItem file = null;

            items = upload.parseRequest(request);
            for (FileItem item : items) {
                String name = item.getFieldName();
                if (name.equals("file_to_upload")) {
                    file = item;
                    break;
                }
            }
            if (file == null || file.getName().equals("")) {
                throw new ErroreGrave("la form non ha inviato il campo file!");
            } else {
                //informazioni
                String nome_e_path = file.getName();
                String estensione = FilenameUtils.getExtension(FilenameUtils.getName(nome_e_path));
                String nome_senza_estensione = FilenameUtils.getBaseName(FilenameUtils.getName(nome_e_path));
                infofile.put("nome_completo", nome_senza_estensione + "." + estensione);
                infofile.put("estensione", estensione);
                infofile.put("nome_senza_estensione", nome_senza_estensione);
                infofile.put("dimensione", file.getSize());
                infofile.put("input_stream", file.getInputStream());
                infofile.put("content_type", file.getContentType());
            }

        } catch (FileUploadException ex) {
            Logger.getLogger(upload_user_img.class.getName()).log(Level.SEVERE, null, ex);
            throw new ErroreGrave("errore libreria apache!");
        }

    }
    return infofile;
}

From source file:eu.webtoolkit.jwt.servlet.WebRequest.java

@SuppressWarnings({ "unchecked", "deprecation" })
private void parse(final ProgressListener progressUpdate) throws IOException {
    if (FileUploadBase.isMultipartContent(this)) {
        try {//from  ww w  . j  a v a  2 s.c om
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            if (progressUpdate != null) {
                upload.setProgressListener(new org.apache.commons.fileupload.ProgressListener() {
                    public void update(long pBytesRead, long pContentLength, int pItems) {
                        progressUpdate.update(WebRequest.this, pBytesRead, pContentLength);
                    }
                });
            }

            // Parse the request
            List items = upload.parseRequest(this);

            parseParameters();

            Iterator itr = items.iterator();

            FileItem fi;
            File f = null;
            while (itr.hasNext()) {
                fi = (FileItem) itr.next();

                // Check if not form field so as to only handle the file inputs
                // else condition handles the submit button input
                if (!fi.isFormField()) {
                    try {
                        f = File.createTempFile("jwt", "jwt");
                        fi.write(f);
                        fi.delete();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    List<UploadedFile> files = files_.get(fi.getFieldName());
                    if (files == null) {
                        files = new ArrayList<UploadedFile>();
                        files_.put(fi.getFieldName(), files);
                    }
                    files.add(new UploadedFile(f.getAbsolutePath(), fi.getName(), fi.getContentType()));
                } else {
                    String[] v = parameters_.get(fi.getFieldName());
                    if (v == null)
                        v = new String[1];
                    else {
                        String[] newv = new String[v.length + 1];
                        for (int i = 0; i < v.length; ++i)
                            newv[i] = v[i];
                        v = newv;
                    }
                    v[v.length - 1] = fi.getString();
                    parameters_.put(fi.getFieldName(), v);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    } else
        parseParameters();
}

From source file:edu.lafayette.metadb.web.controlledvocab.CreateVocab.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*//*from w ww.j a  v a  2 s . c o  m*/
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    String vocabName = null;
    String name = "nothing";
    String status = "Upload failed ";

    try {

        if (ServletFileUpload.isMultipartContent(request)) {
            name = "isMultiPart";
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            InputStream input = null;
            Iterator it = fileItemsList.iterator();
            String result = "";
            String vocabs = null;

            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                result += "CreateVocab: Form Field: " + fileItem.isFormField() + " Field name: "
                        + fileItem.getFieldName() + " Name: " + fileItem.getName() + " String: "
                        + fileItem.getString() + "\n";
                if (fileItem.isFormField()) {
                    /* The file item contains a simple name-value pair of a form field */
                    if (fileItem.getFieldName().equals("vocab-name"))
                        vocabName = fileItem.getString();
                    else if (fileItem.getFieldName().equals("vocab-terms"))
                        vocabs = fileItem.getString();
                } else {

                    @SuppressWarnings("unused")
                    String content = "nothing";
                    /* The file item contains an uploaded file */

                    /* Create new File object
                    File uploadedFile = new File("test.txt");
                    if(!uploadedFile.exists())
                       uploadedFile.createNewFile();
                    // Write the uploaded file to the system
                    fileItem.write(uploadedFile);
                    */
                    name = fileItem.getName();
                    content = fileItem.getContentType();
                    input = fileItem.getInputStream();
                }
            }
            //MetaDbHelper.note(result);
            if (vocabName != null) {
                Set<String> vocabList = new TreeSet<String>();
                if (input != null) {
                    Scanner fileSc = new Scanner(input);
                    while (fileSc.hasNextLine()) {
                        String vocabEntry = fileSc.nextLine();
                        vocabList.add(vocabEntry.trim());
                    }

                    HttpSession session = request.getSession(false);
                    if (session != null) {
                        String userName = (String) session.getAttribute("username");
                        SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                "User " + userName + " created vocab " + vocabName);
                    }
                    status = "Vocab name: " + vocabName + ". File name: " + name + "\n";

                } else {
                    //               status = "Form is not multi-part";
                    //               vocabName = request.getParameter("vocab-name");
                    //               String vocabs = request.getParameter("vocab-terms");
                    MetaDbHelper.note(vocabs);
                    for (String vocab : vocabs.split("\n"))
                        vocabList.add(vocab);
                }
                if (!vocabList.isEmpty()) {
                    if (ControlledVocabDAO.addControlledVocab(vocabName, vocabList))
                        status = "Vocab " + vocabName + " created successfully";
                    else if (ControlledVocabDAO.updateControlledVocab(vocabName, vocabList))
                        status = "Vocab " + vocabName + " updated successfully ";
                    else
                        status = "Vocab " + vocabName + " cannot be updated/created";
                }
            }
        }
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    MetaDbHelper.note(status);
    out.print(status);
    out.flush();
}

From source file:fr.paris.lutece.plugins.suggest.web.SuggestSubmitTypeJspBean.java

/**
 * Get the request data and if there is no error insert the data in the
 * suggestSubmitType object specified in parameter.
 * return null if there is no error or else return the error page url
 * @param multipartRequest the request//from w  ww.  j  a  v  a 2s.  c o  m
 * @param suggestSubmitType the suggestSubmitType Object
 * @return null if there is no error or else return the error page url
 */
private String getSuggestSubmitTypeData(MultipartHttpServletRequest multipartRequest,
        SuggestSubmitType suggestSubmitType) {
    String strName = multipartRequest.getParameter(PARAMETER_NAME);
    String strColor = multipartRequest.getParameter(PARAMETER_COLOR);
    String strParameterizable = multipartRequest.getParameter(PARAMETER_PARAMETERIZABLE);
    Boolean bParameterizable = true;
    String strFieldError = EMPTY_STRING;
    FileItem imageSource = multipartRequest.getFile(PARAMETER_IMAGE_SOURCE);
    String strImageName = FileUploadService.getFileNameOnly(imageSource);
    String strUpdateFile = multipartRequest.getParameter(PARAMETER_UPDATE_FILE);

    if ((strName == null) || strName.trim().equals(EMPTY_STRING)) {
        strFieldError = FIELD_NAME;
    }

    else if ((strParameterizable == null) || strParameterizable.trim().equals(EMPTY_STRING)) {
        bParameterizable = false;
    }

    //Mandatory fields
    if (!strFieldError.equals(EMPTY_STRING)) {
        Object[] tabRequiredFields = { I18nService.getLocalizedString(strFieldError, getLocale()) };

        return AdminMessageService.getMessageUrl(multipartRequest, MESSAGE_MANDATORY_FIELD, tabRequiredFields,
                AdminMessage.TYPE_STOP);
    }

    if ((suggestSubmitType.getIdType() == SuggestUtils.CONSTANT_ID_NULL) || (strUpdateFile != null)) {
        ImageResource image = new ImageResource();
        byte[] baImageSource = imageSource.get();

        if ((strImageName != null) && !strImageName.equals("")) {
            image.setImage(baImageSource);
            image.setMimeType(imageSource.getContentType());
        }

        suggestSubmitType.setPictogram(image);
    }

    suggestSubmitType.setColor(strColor);
    suggestSubmitType.setName(strName);
    suggestSubmitType.setParameterizableInFO(bParameterizable);

    return null;
}

From source file:fr.paris.lutece.plugins.directory.utils.DirectoryUtils.java

/**
 * Do download a file/*from  w  w  w  .j  a v  a  2 s.  c o  m*/
 *
 * @param strUrl
 *            the url of the file to download
 * @return a {@link FileItem}
 */
public static File doDownloadFile(String strUrl) {
    FileItem fileItem = null;
    File file = null;
    DirectoryAsynchronousUploadHandler handler = DirectoryAsynchronousUploadHandler.getHandler();

    try {
        fileItem = handler.doDownloadFile(strUrl);
    } catch (BlobStoreClientException e) {
        AppLogService.error(e);
    }

    if (fileItem != null) {
        if (fileItem.getSize() < Integer.MAX_VALUE) {
            PhysicalFile physicalFile = new PhysicalFile();
            physicalFile.setValue(fileItem.get());

            String strFileName = fileItem.getName();

            if (StringUtils.isNotBlank(strFileName)) {
                String strExtension = StringUtils.EMPTY;
                int nLastIndexOfDot = strFileName.lastIndexOf(CONSTANT_DOT);

                if (nLastIndexOfDot != DirectoryUtils.CONSTANT_ID_NULL) {
                    strExtension = strFileName.substring(nLastIndexOfDot + 1);
                }

                file = new File();
                file.setPhysicalFile(physicalFile);
                file.setSize((int) fileItem.getSize());
                file.setTitle(strFileName);

                if (StringUtils.isNotBlank(fileItem.getContentType())) {
                    file.setMimeType(fileItem.getContentType());
                } else {
                    file.setMimeType(FileSystemUtil.getMIMEType(strFileName));
                }

                file.setExtension(strExtension);
            }
        } else {
            AppLogService.error(
                    "DirectoryUtils : File too big ! fr.paris.lutece.plugins.directory.business.File.setSize "
                            + "must have Integer parameter, in other words a size lower than '"
                            + Integer.MAX_VALUE + "'");
        }
    }

    return file;
}

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//from  w  ww .  j  ava  2 s  . com
 */
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);
        }
    }
}

From source file:it.infn.ct.molon_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
 * All form' input items are identified by the 'name' input property inside
 * the jsp file//from w  ww.  ja v a  2s . c  o m
 * @param request ActionRequest instance (processAction)
 * @param appInput AppInput instance storing the jobSubmission data
 */

void getInputForm(ActionRequest request, molon_portlet.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 = "";
            int i = 0;
            int j = 0;
            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
                switch (molon_portlet.inputControlsIds.valueOf(fieldName)) {

                case jobPID:
                    logstring += LS + "FIELD IS A JOB PID  WITH NAME : '" + item.getString() + "'";
                    appInput.jobPID = item.getString();
                    break;
                case inputURL:
                    logstring += LS + "FIELD IS AN INPUT URL  WITH NAME : '" + item.getString() + "'";
                    appInput.inputURL = item.getString();
                    break;
                case JobIdentifier:
                    logstring += LS + "FIELD IS A JOB IDENTIFIER  WITH NAME : '" + item.getString() + "'";
                    appInput.jobIdentifier = item.getString();
                    break;
                case file_inputFile:
                    if (fileName == "")
                        break;
                    logstring += LS + "FIELD IS A FILE WITH NAME : '" + fileName + "'";
                    appInput.inputFile = appInput.path + "/" + fileName;
                    logstring += LS + "COPYING IT TO PATH : '" + appInput.path + "'";
                    copyFile(item, appInput.inputFile);

                    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 + "jobPID: '" + appInput.jobPID + "'"
            + LS + "inputURL: '" + appInput.inputURL + "'" + LS + "inputFile: '" + appInput.inputFile + "'"
            + LS);

}