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

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

Introduction

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

Prototype

String getContentType();

Source Link

Document

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

Usage

From source file:fi.iki.elonen.SimpleWebServer.java

private Response getUploadMsgAndExec(IHTTPSession session) throws FileUploadException, IOException {
    uploader = new NanoFileUpload(new DiskFileItemFactory());
    files = new HashMap<String, List<FileItem>>();
    FileItemIterator iter = uploader.getItemIterator(session);
    String fileName = "", newFileName = "";
    try {/*  w w w  . j a  v  a2 s .  c  om*/
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            fileName = item.getName();
            newFileName = rootDirs.get(0) + "/".concat(fileName);
            FileItem fileItem = uploader.getFileItemFactory().createItem(item.getFieldName(),
                    item.getContentType(), item.isFormField(), newFileName);
            files.put(fileItem.getFieldName(), Arrays.asList(new FileItem[] { fileItem }));

            try {
                Streams.copy(item.openStream(), (new FileOutputStream(newFileName)), true);
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
            fileItem.setHeaders(item.getHeaders());
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return newFixedLengthResponse(
            "<html><body> \n File: " + fileName + " upload to " + newFileName + "! \n </body></html>\n");
}

From source file:ca.nrc.cadc.beacon.web.resources.FileItemServerResource.java

/**
 * Perform the actual upload.//from  ww w. jav  a  2 s.  co  m
 *
 * @param fileItemStream The upload file item stream.
 * @return The URI to the new node.
 * @throws IOException If anything goes wrong.
 */
VOSURI upload(final FileItemStream fileItemStream)
        throws IOException, IllegalArgumentException, NodeAlreadyExistsException {
    final String filename = fileItemStream.getName();

    if (fileValidator.validateString(filename)) {
        final String path = getCurrentItemURI().getPath() + "/" + URLEncoder.encode(filename, "UTF-8");
        final DataNode dataNode = new DataNode(toURI(path));

        // WebRT 19564: Add content type to the response of
        // uploaded items.
        final List<NodeProperty> properties = new ArrayList<>();

        properties.add(new NodeProperty(VOS.PROPERTY_URI_TYPE, fileItemStream.getContentType()));
        properties.add(new NodeProperty(VOS.PROPERTY_URI_CONTENTLENGTH,
                Long.toString(getRequest().getEntity().getSize())));

        dataNode.setProperties(properties);

        try (final InputStream inputStream = fileItemStream.openStream()) {
            upload(inputStream, dataNode);
        }

        return dataNode.getUri();
    } else {
        throw new IllegalArgumentException("Name is required and cannot contain characters \n"
                + "outside of alphanumeric and _-()=+!,;:@&*$.");
    }
}

From source file:act.util.UploadFileStorageService.java

private ISObject _store(FileItemStream fileItemStream) throws IOException {
    String filename = fileItemStream.getName();
    String key = newKey(filename);
    File tmpFile = getFile(key);/*from   w  w  w.  j  ava 2s .  c o  m*/
    InputStream input = fileItemStream.openStream();
    ThresholdingByteArrayOutputStream output = new ThresholdingByteArrayOutputStream(inMemoryCacheThreshold,
            tmpFile);
    IO.copy(input, output);

    ISObject retVal;
    if (output.exceedThreshold) {
        retVal = getFull(key);
    } else {
        int size = output.written;
        byte[] buf = output.buf();
        retVal = SObject.of(key, buf, size);
    }

    if (S.notBlank(filename)) {
        retVal.setFilename(filename);
    }
    String contentType = fileItemStream.getContentType();
    if (null != contentType) {
        retVal.setContentType(contentType);
    }
    return retVal;
}

From source file:com.manydesigns.portofino.stripes.StreamingCommonsMultipartWrapper.java

/**
 * Pseudo-constructor that allows the class to perform any initialization necessary.
 *
 * @param request     an HttpServletRequest that has a content-type of multipart.
 * @param tempDir a File representing the temporary directory that can be used to store
 *        file parts as they are uploaded if this is desirable
 * @param maxPostSize the size in bytes beyond which the request should not be read, and a
 *                    FileUploadLimitExceeded exception should be thrown
 * @throws IOException if a problem occurs processing the request of storing temporary
 *                    files/*from  w w  w.ja  v a2 s.co  m*/
 * @throws FileUploadLimitExceededException if the POST content is longer than the
 *                     maxPostSize supplied.
 */
@SuppressWarnings("unchecked")
public void build(HttpServletRequest request, File tempDir, long maxPostSize)
        throws IOException, FileUploadLimitExceededException {
    try {
        this.charset = request.getCharacterEncoding();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(tempDir);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxPostSize);
        FileItemIterator iterator = upload.getItemIterator(request);

        Map<String, List<String>> params = new HashMap<String, List<String>>();

        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();

            // If it's a form field, add the string value to the list
            if (item.isFormField()) {
                List<String> values = params.get(item.getFieldName());
                if (values == null) {
                    values = new ArrayList<String>();
                    params.put(item.getFieldName(), values);
                }
                values.add(charset == null ? IOUtils.toString(stream) : IOUtils.toString(stream, charset));
            }
            // Else store the file param
            else {
                TempFile tempFile = TempFileService.getInstance().newTempFile(item.getContentType(),
                        item.getName());
                int size = IOUtils.copy(stream, tempFile.getOutputStream());
                FileItem fileItem = new FileItem(item.getName(), item.getContentType(), tempFile, size);
                files.put(item.getFieldName(), fileItem);
            }
        }

        // Now convert them down into the usual map of String->String[]
        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
            List<String> values = entry.getValue();
            this.parameters.put(entry.getKey(), values.toArray(new String[values.size()]));
        }
    } catch (FileUploadBase.SizeLimitExceededException slee) {
        throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize());
    } catch (FileUploadException fue) {
        IOException ioe = new IOException("Could not parse and cache file upload data.");
        ioe.initCause(fue);
        throw ioe;
    }

}

From source file:com.liferay.faces.bridge.context.map.internal.MultiPartFormDataProcessorImpl.java

@Override
public Map<String, List<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig,
        FacesRequestParameterMap facesRequestParameterMap) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;

    PortletSession portletSession = clientDataRequest.getPortletSession();

    String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig);

    // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = portletSession.getId();

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK);

    File uploadedFilesPath = new File(uploadedFilesDir, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();//ww w.  ja  v  a 2 s . c  o m
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    long uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getLongValue(portletConfig);

    // Parse the request parameters and save all uploaded files in a map.
    PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
    portletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

    // FACES-271: Include name+value pairs found in the ActionRequest.
    Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();

    for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {

        String parameterName = mapEntry.getKey();
        String[] parameterValues = mapEntry.getValue();

        if (parameterValues.length > 0) {

            for (String parameterValue : parameterValues) {
                facesRequestParameterMap.addValue(parameterName, parameterValue);
            }
        }
    }

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder
            .getFactory(UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        if (clientDataRequest instanceof ResourceRequest) {
            ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
        } else {
            ActionRequest actionRequest = (ActionRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
        }

        if (fileItemIterator != null) {

            int totalFiles = 0;
            String namespace = facesRequestParameterMap.getNamespace();

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a simple form-field, then save the form field value in the map.
                    if (diskFileItem.isFormField()) {
                        String characterEncoding = clientDataRequest.getCharacterEncoding();
                        String requestParameterValue = null;

                        if (characterEncoding == null) {
                            requestParameterValue = diskFileItem.getString();
                        } else {
                            requestParameterValue = diskFileItem.getString(characterEncoding);
                        }

                        facesRequestParameterMap.addValue(fieldName, requestParameterValue);
                    } else {

                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath);
                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

From source file:com.google.sampling.experiential.server.EventServlet.java

private void processCsvUpload(HttpServletRequest req, HttpServletResponse resp) {
    PrintWriter out = null;/* ww w .  j a v  a  2s. c o  m*/
    try {
        out = resp.getWriter();
    } catch (IOException e1) {
        log.log(Level.SEVERE, "Cannot get an output PrintWriter!");
    }
    try {
        boolean isDevInstance = isDevInstance(req);
        ServletFileUpload fileUploadTool = new ServletFileUpload();
        fileUploadTool.setSizeMax(50000);
        resp.setContentType("text/html;charset=UTF-8");

        FileItemIterator iterator = fileUploadTool.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = null;
            try {
                in = item.openStream();

                if (item.isFormField()) {
                    out.println("Got a form field: " + item.getFieldName());
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();

                    out.println("--------------");
                    out.println("fileName = " + fileName);
                    out.println("field name = " + fieldName);
                    out.println("contentType = " + contentType);

                    String fileContents = null;
                    fileContents = IOUtils.toString(in);
                    out.println("length: " + fileContents.length());
                    out.println(fileContents);
                    saveCSV(fileContents, isDevInstance);
                }
            } catch (ParseException e) {
                log.info("Parse Exception: " + e.getMessage());
                out.println("Could not parse your csv upload: " + e.getMessage());
            } finally {
                in.close();
            }
        }
    } catch (SizeLimitExceededException e) {
        log.info("SizeLimitExceededException: " + e.getMessage());
        out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                + e.getActualSize() + ")");
        return;
    } catch (IOException e) {
        log.severe("IOException: " + e.getMessage());
        out.println("Error in receiving file.");
    } catch (FileUploadException e) {
        log.severe("FileUploadException: " + e.getMessage());
        out.println("Error in receiving file.");
    }
}

From source file:act.data.ApacheMultipartParser.java

@Override
public Map<String, String[]> parse(ActionContext context) {
    H.Request request = context.req();
    InputStream body = request.inputStream();
    Map<String, String[]> result = new HashMap<>();
    try {// w ww .j  av a 2  s.c om
        FileItemIteratorImpl iter = new FileItemIteratorImpl(body, request.header("content-type"),
                request.characterEncoding());
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            ISObject sobj = UploadFileStorageService.store(item, context.app());
            if (sobj.getLength() == 0L) {
                continue;
            }
            String fieldName = item.getFieldName();
            if (item.isFormField()) {
                // must resolve encoding
                String _encoding = request.characterEncoding(); // this is our default
                String _contentType = item.getContentType();
                if (_contentType != null) {
                    ContentTypeWithEncoding contentTypeEncoding = ContentTypeWithEncoding.parse(_contentType);
                    if (contentTypeEncoding.encoding != null) {
                        _encoding = contentTypeEncoding.encoding;
                    }
                }

                mergeValueInMap(result, fieldName, sobj.asString(Charset.forName(_encoding)));
            } else {
                context.addUpload(item.getFieldName(), sobj);
                mergeValueInMap(result, fieldName, fieldName);
            }
        }
    } catch (FileUploadIOException e) {
        throw E.ioException("Error when handling upload", e);
    } catch (IOException e) {
        throw E.ioException("Error when handling upload", e);
    } catch (FileUploadException e) {
        throw E.ioException("Error when handling upload", e);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new UnexpectedException(e);
    }
    return result;
}

From source file:com.artgameweekend.projects.art.web.TagUploadServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {//w  ww .  ja  va  2s .  c om

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        upload.setSizeMax(500000);
        res.setContentType(Constants.CONTENT_TYPE_TEXT);
        PrintWriter out = res.getWriter();
        byte[] image = null;

        Tag tag = new Tag();
        TagImage tagImage = new TagImage();
        TagThumbnail tagThumbnail = new TagThumbnail();
        String contentType = null;
        boolean bLandscape = false;

        try {
            FileItemIterator iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream in = item.openStream();

                if (item.isFormField()) {
                    out.println("Got a form field: " + item.getFieldName());
                    if (Constants.PARAMATER_NAME.equals(item.getFieldName())) {
                        tag.setName(IOUtils.toString(in));
                    }
                    if (Constants.PARAMATER_LAT.equals(item.getFieldName())) {
                        tag.setLat(Double.parseDouble(IOUtils.toString(in)));
                    }
                    if (Constants.PARAMATER_LON.equals(item.getFieldName())) {
                        tag.setLon(Double.parseDouble(IOUtils.toString(in)));
                    }
                    if (Constants.PARAMATER_LANDSCAPE.equals(item.getFieldName())) {
                        bLandscape = IOUtils.toString(in).equals("on");
                    }
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    contentType = item.getContentType();

                    out.println("--------------");
                    out.println("fileName = " + fileName);
                    out.println("field name = " + fieldName);
                    out.println("contentType = " + contentType);

                    try {
                        image = IOUtils.toByteArray(in);
                    } finally {
                        IOUtils.closeQuietly(in);
                    }

                }
            }
        } catch (SizeLimitExceededException e) {
            out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                    + e.getActualSize() + ")");
        }

        contentType = (contentType != null) ? contentType : "image/jpeg";

        if (bLandscape) {
            image = rotate(image);
        }
        tagImage.setImage(image);
        tagImage.setContentType(contentType);
        tagThumbnail.setImage(createThumbnail(image));
        tagThumbnail.setContentType(contentType);

        TagImageDAO daoImage = new TagImageDAO();
        daoImage.create(tagImage);

        TagThumbnailDAO daoThumbnail = new TagThumbnailDAO();
        daoThumbnail.create(tagThumbnail);

        TagDAO dao = new TagDAO();
        tag.setKeyImage(tagImage.getKey());
        tag.setKeyThumbnail(tagThumbnail.getKey());
        tag.setDate(new Date().getTime());
        dao.create(tag);

    } catch (Exception ex) {

        throw new ServletException(ex);
    }
}

From source file:com.glaf.core.web.servlet.FileUploadServlet.java

public void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html;charset=UTF-8");
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    if (loginContext == null) {
        return;/*from   w  w w.ja va2s .  co  m*/
    }
    String serviceKey = request.getParameter("serviceKey");
    String type = request.getParameter("type");
    if (StringUtils.isEmpty(type)) {
        type = "0";
    }
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap:" + paramMap);
    String rootDir = SystemProperties.getConfigRootPath();

    InputStream inputStream = null;
    try {
        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        // threshold ???? 8M
        diskFactory.setSizeThreshold(8 * FileUtils.MB_SIZE);
        // repository 
        diskFactory.setRepository(new File(rootDir + "/temp"));
        ServletFileUpload upload = new ServletFileUpload(diskFactory);
        int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
        if (maxUploadSize == 0) {
            maxUploadSize = conf.getInt("upload.maxUploadSize", 50);// 50MB
        }
        maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;
        logger.debug("maxUploadSize:" + maxUploadSize);

        upload.setHeaderEncoding("UTF-8");
        upload.setSizeMax(maxUploadSize);
        upload.setFileSizeMax(maxUploadSize);
        String uploadDir = Constants.UPLOAD_PATH;

        if (ServletFileUpload.isMultipartContent(request)) {
            logger.debug("#################start upload process#########################");
            FileItemIterator iter = upload.getItemIterator(request);
            PrintWriter out = response.getWriter();
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    // ????
                    String autoCreatedDateDirByParttern = "yyyy/MM/dd";
                    String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(),
                            autoCreatedDateDirByParttern);

                    File savePath = new File(rootDir + uploadDir + autoCreatedDateDir);
                    if (!savePath.exists()) {
                        savePath.mkdirs();
                    }

                    String fileId = UUID32.getUUID();
                    String fileName = savePath + "/" + fileId;

                    BlobItem dataFile = new BlobItemEntity();
                    dataFile.setLastModified(System.currentTimeMillis());
                    dataFile.setCreateBy(loginContext.getActorId());
                    dataFile.setFileId(fileId);
                    dataFile.setPath(uploadDir + autoCreatedDateDir + "/" + fileId);
                    dataFile.setFilename(item.getName());
                    dataFile.setName(item.getName());
                    dataFile.setContentType(item.getContentType());
                    dataFile.setType(type);
                    dataFile.setStatus(0);
                    dataFile.setServiceKey(serviceKey);
                    getBlobService().insertBlob(dataFile);

                    inputStream = item.openStream();

                    FileUtils.save(fileName, inputStream);

                    logger.debug(fileName + " save ok.");

                    out.print(fileId);
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.close(inputStream);
    }
}

From source file:com.liferay.faces.bridge.context.map.MultiPartFormDataProcessorImpl.java

@Override
public Map<String, Collection<UploadedFile>> process(ClientDataRequest clientDataRequest,
        PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap) {

    Map<String, Collection<UploadedFile>> uploadedFileMap = null;

    PortletSession portletSession = clientDataRequest.getPortletSession();

    String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig);

    // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = portletSession.getId();

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK);

    File uploadedFilesPath = new File(uploadedFilesDir, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();//w  w w. j  a  v  a  2  s .com
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    int uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getIntegerValue(portletConfig);

    // Parse the request parameters and save all uploaded files in a map.
    PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
    portletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, Collection<UploadedFile>>();

    // FACES-271: Include name+value pairs found in the ActionRequest.
    Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();

    for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {

        String parameterName = mapEntry.getKey();
        String[] parameterValues = mapEntry.getValue();

        if (parameterValues.length > 0) {

            for (String parameterValue : parameterValues) {
                facesRequestParameterMap.addValue(parameterName, parameterValue);
            }
        }
    }

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder
            .getFactory(UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        if (clientDataRequest instanceof ResourceRequest) {
            ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
        } else {
            ActionRequest actionRequest = (ActionRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
        }

        boolean optimizeNamespace = PortletConfigParam.OptimizePortletNamespace.getBooleanValue(portletConfig);

        if (fileItemIterator != null) {

            int totalFiles = 0;
            String namespace = facesRequestParameterMap.getNamespace();

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // If namespace optimization is enabled and the namespace is present in the field name,
                    // then remove the portlet namespace from the field name.
                    if (optimizeNamespace) {
                        int pos = fieldName.indexOf(namespace);

                        if (pos >= 0) {
                            fieldName = fieldName.substring(pos + namespace.length());
                        }
                    }

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a simple form-field, then save the form field value in the map.
                    if (diskFileItem.isFormField()) {
                        String characterEncoding = clientDataRequest.getCharacterEncoding();
                        String requestParameterValue = null;

                        if (characterEncoding == null) {
                            requestParameterValue = diskFileItem.getString();
                        } else {
                            requestParameterValue = diskFileItem.getString(characterEncoding);
                        }

                        facesRequestParameterMap.addValue(fieldName, requestParameterValue);
                    } else {

                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath);
                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}