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

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

Introduction

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

Prototype

public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException 

Source Link

Document

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

Usage

From source file:org.odk.voice.storage.MultiPartFormData.java

/**
 * Construct a mult-part form data container by parsing
 * a multi part form request into a set of multipartformitems. The
 * information are stored in items and are indexed by either 
 * the field name or the file name (or both) provided in the http submission
 * //from w ww . j  a  v  a2 s  .co m
 * @param req
 *     an HTTP request from a multipart form 
        
 * @throws FileUploadException
 * @throws IOException
 */
public MultiPartFormData(HttpServletRequest req) throws FileUploadException, IOException {

    fieldNameMap = new HashMap<String, MultiPartFormItem>();
    fileNameMap = new HashMap<String, MultiPartFormItem>();

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setFileSizeMax(FileConstants.MAX_FILE_SIZE);

    FileItemIterator items = upload.getItemIterator(req);
    while (items.hasNext()) {
        FileItemStream item = items.next();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        BufferedInputStream formStream = new BufferedInputStream(item.openStream());

        // TODO: determine ways to possibly improve efficiency
        int nextByte = formStream.read();
        while (nextByte != -1) {
            byteStream.write(nextByte);
            nextByte = formStream.read();
        }

        MultiPartFormItem data = new MultiPartFormItem(item.getFieldName(), item.getName(),
                item.getContentType(), byteStream.toByteArray());

        String fieldName = item.getFieldName();
        if (fieldName != null) {
            fieldNameMap.put(fieldName, data);
        }

        String fileName = item.getName();
        if (fileName != null) {
            // TODO: possible bug in ODK collect is truncating file extension
            // may need to remove this code after ODK collect is fixed
            int indexOfExtension = fileName.lastIndexOf(".");
            if (indexOfExtension > 0) {
                fileNameMap.put(fileName.substring(0, indexOfExtension), data);
            }
            fileNameMap.put(fileName, data);
        }
    }
}

From source file:org.olat.core.gui.components.form.flexible.impl.Form.java

/**
 * Internal helper to initialize the request parameter map an to temporary store the uploaded files when a multipart request is used. The files are stored to a
 * temporary location and a filehandle is added to the requestMultipartFiles map for later retrieval by the responsible FormItem.
 * //  w w  w .  jav  a2s.c o m
 * @param ureq
 */
private void doInitRequestParameterAndMulipartData(UserRequest ureq) {
    // First fill parameter map either from multipart data or standard http request
    if (isMultipartEnabled() && ServletFileUpload.isMultipartContent(ureq.getHttpReq())) {
        long uploadSize = -1; // default unlimited
        // Limit size of complete upload form: upload size limit + 500k for
        // other input fields
        if (multipartUploadMaxSizeKB > -1) {
            uploadSize = (multipartUploadMaxSizeKB * 1024l * 1024l) + 512000l;
        }

        // Create a new file upload handler, use commons fileupload streaming
        // API to save files right to the tmp location
        ServletFileUpload uploadParser = new ServletFileUpload();
        uploadParser.setSizeMax(uploadSize);
        // Parse the request
        try {
            FileItemIterator iter = uploadParser.getItemIterator(ureq.getHttpReq());
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String itemName = item.getFieldName();
                InputStream itemStream = item.openStream();
                if (item.isFormField()) {
                    // Normal form item
                    // analog to ureq.getParameter in non-multipart mode
                    String value = Streams.asString(itemStream, "UTF-8");
                    addRequestParameter(itemName, value);
                } else {
                    // File item, store it to temp location
                    String fileName = item.getName();
                    // Cleanup IE filenames that are absolute
                    int slashpos = fileName.lastIndexOf("/");
                    if (slashpos != -1)
                        fileName = fileName.substring(slashpos + 1);
                    slashpos = fileName.lastIndexOf("\\");
                    if (slashpos != -1)
                        fileName = fileName.substring(slashpos + 1);

                    File tmpFile = new File(System.getProperty("java.io.tmpdir") + File.separator + "upload-"
                            + CodeHelper.getGlobalForeverUniqueID());

                    try {
                        FileUtils.save(itemStream, tmpFile);
                        // Only save non-empty file transfers, ignore empty transfers
                        // (e.g. already submitted in a previous form submit, not an error!)

                        // Removing empty file check for now ... was introduced to cope with
                        // browser trouble which probably is not there any more ...
                        // so empty fileName means nothing selected in the file element

                        // if (tmpFile.length() > 0) {
                        if (fileName.length() > 0) {
                            // a file was selected
                            // Save file and also original file name
                            requestMultipartFiles.put(itemName, tmpFile);
                            requestMultipartFileNames.put(itemName, fileName);
                            requestMultipartFileMimeTypes.put(itemName, item.getContentType());
                        } else {
                            if (tmpFile.exists())
                                tmpFile.delete();
                        }
                    } catch (OLATRuntimeException e) {
                        // Could not save stream for whatever reason, cleanup temp file and delegate exception
                        if (tmpFile.exists())
                            tmpFile.delete();

                        if (e.getCause() instanceof MalformedStreamException) {
                            logWarn("Could not read uploaded file >" + fileName
                                    + "< from stream. Possibly an attempt to upload a directory instead of a file (happens on Mac)",
                                    e);
                            return;
                        }

                        throw new OLATRuntimeException("Could not save uploaded file", e);
                    }
                }
            }
        } catch (SizeLimitExceededException sizeLimitExceededException) {
            logError("Error while dispatching multipart form: file limit (" + uploadSize + ") exceeded",
                    sizeLimitExceededException);
            requestError = REQUEST_ERROR_UPLOAD_LIMIT_EXCEEDED;
        } catch (IOException e) {
            logWarn("Error while dispatching multipart form: ioexception", e);
            requestError = REQUEST_ERROR_GENERAL;
        } catch (Exception e) {
            logError("Error while dispatching multipart form: general exception", e);
            requestError = REQUEST_ERROR_GENERAL;
        }
    } else {
        // Get parameters the standard way
        logDebug("Dispatching non-multipart form", null);
        Set<String> keys = ureq.getParameterSet();
        for (String key : keys) {
            String[] values = ureq.getHttpReq().getParameterValues(key);
            if (values != null) {
                requestParams.put(key, values);
            } else {
                addRequestParameter(key, ureq.getParameter(key));
            }
        }
    }
}

From source file:org.olat.restapi.support.MultipartReader.java

private final void apache(HttpServletRequest request, long uploadLimit) {
    ServletFileUpload uploadParser = new ServletFileUpload();
    uploadParser.setSizeMax((uploadLimit * 1024l) + 512000l);
    // Parse the request
    try {/*from ww w  . j av  a2s .c  o  m*/
        FileItemIterator iter = uploadParser.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String itemName = item.getFieldName();
            InputStream itemStream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(itemStream, "UTF-8");
                fields.put(itemName, value);
            } else {
                // File item, store it to temp location
                filename = item.getName();
                contentType = item.getContentType();

                if (filename != null) {
                    filename = UUID.randomUUID().toString().replace("-", "") + "_" + filename;
                } else {
                    filename = "upload-" + UUID.randomUUID().toString().replace("-", "");
                }
                file = new File(WebappHelper.getTmpDir(), filename);
                try {
                    save(itemStream, file);
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }
    } catch (Exception e) {
        log.error("", e);
    }
}

From source file:org.onecmdb.ui.gwt.desktop.server.command.ChangeUploadCommand.java

private void getFileItem(HttpServletRequest request) throws FileUploadException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        throw new IllegalArgumentException("Not multipart...");
    }/* w w w  . j  a v a 2  s  . com*/

    ServletFileUpload upload = new ServletFileUpload();

    List<String> mdrEntries = new ArrayList<String>();

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();

        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
        } else {
            System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
            // Process the input stream
        }
        String mdrEntry = handleInput(name, stream);
        mdrEntries.add(mdrEntry);
    }
    commitContent(mdrEntries);
}

From source file:org.onecmdb.ui.gwt.desktop.server.servlet.ContentServiceServlet.java

private void getFileItem(HttpServletRequest request, File root) throws FileUploadException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        throw new IllegalArgumentException("Not multipart...");
    }// w ww .ja  v a  2 s .c o  m

    ServletFileUpload upload = new ServletFileUpload();

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(request);

    String fileName = null;
    String path = null;
    while (iter.hasNext()) {
        FileItemStream item = iter.next();

        String name = item.getFieldName();
        InputStream stream = item.openStream();
        System.out.println("Name=" + item.getName());

        if (item.isFormField()) {
            String value = Streams.asString(stream);
            System.out.println("FormField " + name + "=" + value);
            if (name.equals("name")) {
                fileName = value;
            }
            if (name.equals("path")) {
                path = value;
            }

        } else {
            System.out.println("File field " + name + " with file name " + item.getName() + " detected.");

            File output = new File(root, path + "/" + fileName);
            System.out.println("Write upload to " + output.getPath());

            IOUtil.copyCompletely(stream, new FileOutputStream(output));
        }

    }
}

From source file:org.opencastproject.fileupload.rest.FileUploadRestService.java

@POST
@Produces(MediaType.APPLICATION_XML)//from w  ww  .j a  v a 2  s.  c o  m
@Path("job/{jobID}")
@RestQuery(name = "newjob", description = "Appends the next chunk of data to the file on the server.", pathParameters = {
        @RestParameter(description = "The ID of the upload job", isRequired = false, name = "jobID", type = RestParameter.Type.STRING) }, restParameters = {
                @RestParameter(description = "The number of the current chunk", isRequired = false, name = "chunknumber", type = RestParameter.Type.STRING),
                @RestParameter(description = "The payload", isRequired = false, name = "filedata", type = RestParameter.Type.FILE) }, reponses = {
                        @RestResponse(description = "the chunk data was successfully appended to file on server", responseCode = HttpServletResponse.SC_OK),
                        @RestResponse(description = "the upload job was not found", responseCode = HttpServletResponse.SC_NOT_FOUND),
                        @RestResponse(description = "the request was malformed", responseCode = HttpServletResponse.SC_BAD_REQUEST) }, returnDescription = "The XML representation of the updated upload job")
public Response postPayload(@PathParam("jobID") String jobId, @Context HttpServletRequest request) {
    try {
        if (!ServletFileUpload.isMultipartContent(request)) { // make sure request is "multipart/form-data"
            throw new FileUploadException("Request is not of type multipart/form-data");
        }
        if (uploadService.hasJob(jobId)) { // testing for existence of job here already so we can generate a 404 early
            long chunkNum = 0;
            FileUploadJob job = uploadService.getJob(jobId);
            ServletFileUpload upload = new ServletFileUpload();
            for (FileItemIterator iter = upload.getItemIterator(request); iter.hasNext();) {
                FileItemStream item = iter.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    if (REQUESTFIELD_CHUNKNUM.equalsIgnoreCase(name)) {
                        chunkNum = Long.parseLong(Streams.asString(item.openStream()));
                    }
                } else if (REQUESTFIELD_DATA.equalsIgnoreCase(item.getFieldName())) {
                    uploadService.acceptChunk(job, chunkNum, item.openStream());
                    return Response.ok(job).build();
                }
            }
            throw new FileUploadException("No payload!");
        } else {
            log.warn("Upload job not found: " + jobId);
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return Response.serverError().entity(buildUnexpectedErrorMessage(e)).build();
    }
}

From source file:org.opencastproject.ingest.endpoint.IngestRestService.java

/**
 * Add an elements to a MediaPackage and keeps track of the progress of the upload. Returns an HTML that triggers the
 * host sites UploadListener.uploadComplete javascript event Returns an HTML that triggers the host sites
 * UploadListener.uplaodFailed javascript event in case of error
 * //from  w  w  w.j  av a 2  s.  c o m
 * @param jobId
 *          of the upload job
 * @param request
 *          containing the file, the flavor and the MediaPackage to which it should be added
 * @return HTML that calls the UploadListener.uploadComplete javascript handler
 */
@POST
@Path("addElementMonitored/{jobId}")
@Produces(MediaType.TEXT_HTML)
public Response addElementMonitored(@PathParam("jobId") String jobId, @Context HttpServletRequest request) {
    UploadJob job = null;
    MediaPackage mp = null;
    String fileName = null;
    MediaPackageElementFlavor flavor = null;
    String elementType = "track";
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        try { // try to get UploadJob, responde 404 if not successful
            // job = em.find(UploadJob.class, jobId);
            if (jobs.containsKey(jobId)) {
                job = jobs.get(jobId);
            } else {
                throw new NoResultException("Job not found");
            }
        } catch (NoResultException e) {
            logger.warn("Upload job not found for Id: " + jobId);
            return buildUploadFailedRepsonse(job);
        }
        if (ServletFileUpload.isMultipartContent(request)) {
            ServletFileUpload upload = new ServletFileUpload();
            UploadProgressListener listener = new UploadProgressListener(job, this.emf);
            upload.setProgressListener(listener);
            for (FileItemIterator iter = upload.getItemIterator(request); iter.hasNext();) {
                FileItemStream item = iter.next();
                String fieldName = item.getFieldName();
                if ("mediaPackage".equalsIgnoreCase(fieldName)) {
                    mp = factory.newMediaPackageBuilder().loadFromXml(item.openStream());
                } else if ("flavor".equals(fieldName)) {
                    String flavorString = Streams.asString(item.openStream());
                    if (flavorString != null) {
                        flavor = MediaPackageElementFlavor.parseFlavor(flavorString);
                    }
                } else if ("elementType".equalsIgnoreCase(fieldName)) {
                    String typeString = Streams.asString(item.openStream());
                    if (typeString != null) {
                        elementType = typeString;
                    }
                } else if ("file".equalsIgnoreCase(fieldName)) {
                    fileName = item.getName();
                    job.setFilename(fileName);
                    if ((mp != null) && (flavor != null) && (fileName != null)) {
                        // decide which element type to add
                        if ("TRACK".equalsIgnoreCase(elementType)) {
                            mp = ingestService.addTrack(item.openStream(), fileName, flavor, mp);
                        } else if ("CATALOG".equalsIgnoreCase(elementType)) {
                            logger.info("Adding Catalog: " + fileName + " - " + flavor);
                            mp = ingestService.addCatalog(item.openStream(), fileName, flavor, mp);
                        }
                        InputStream is = null;
                        try {
                            is = getClass().getResourceAsStream("/templates/complete.html");
                            String html = IOUtils.toString(is, "UTF-8");
                            html = html.replaceAll("\\{mediaPackage\\}", MediaPackageParser.getAsXml(mp));
                            html = html.replaceAll("\\{jobId\\}", job.getId());
                            return Response.ok(html).build();
                        } finally {
                            IOUtils.closeQuietly(is);
                        }
                    }
                }
            }
        } else {
            logger.warn("Job " + job.getId() + ": message is not multipart/form-data encoded");
        }
        return buildUploadFailedRepsonse(job);
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        return buildUploadFailedRepsonse(job);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opendatakit.aggregate.parser.MultiPartFormData.java

/**
 * Construct a mult-part form data container by parsing a multi part form
 * request into a set of multipartformitems. The information are stored in
 * items and are indexed by either the field name or the file name (or both)
 * provided in the http submission//  w w  w.  j  av  a 2s  .co  m
 * 
 * @param req
 *            an HTTP request from a multipart form
 * 
 * @throws FileUploadException
 * @throws IOException
 */
public MultiPartFormData(HttpServletRequest req) throws FileUploadException, IOException {

    simpleFieldNameMap = new HashMap<String, String>();
    fieldNameMap = new HashMap<String, MultiPartFormItem>();
    fileNameMap = new HashMap<String, MultiPartFormItem>();
    fileNameWithoutExtensionNameMap = new HashMap<String, MultiPartFormItem>();

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    int size = req.getContentLength();
    if (size > 0) {
        upload.setFileSizeMax(size);
    } else {
        upload.setFileSizeMax(ParserConsts.FILE_SIZE_MAX);
    }

    List<MultiPartFormItem> fileNameList = new ArrayList<MultiPartFormItem>();

    FileItemIterator items = upload.getItemIterator(req);
    while (items.hasNext()) {
        FileItemStream item = items.next();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        BufferedInputStream formStream = new BufferedInputStream(item.openStream());

        // TODO: determine ways to possibly improve efficiency
        int nextByte = formStream.read();
        while (nextByte != -1) {
            byteStream.write(nextByte);
            nextByte = formStream.read();
        }
        formStream.close();

        if (item.isFormField()) {
            simpleFieldNameMap.put(item.getFieldName(), byteStream.toString());
        } else {
            MultiPartFormItem data = new MultiPartFormItem(item.getFieldName(), item.getName(),
                    item.getContentType(), byteStream);

            String fieldName = item.getFieldName();
            if (fieldName != null) {
                fieldNameMap.put(fieldName, data);
            }
            String fileName = item.getName();
            if (fileName != null && fileName.length() != 0) {
                fileNameList.add(data);
            }
        }
    }

    // Find the common prefix to the filenames being uploaded...
    // Deal with Windows backslash file separator...
    boolean first = true;
    String[] commonPath = null;
    int commonPrefix = 0;
    for (MultiPartFormItem e : fileNameList) {
        String fullFilePath = e.getFilename();
        if (first) {
            commonPath = fullFilePath.split("[/\\\\]");
            commonPrefix = commonPath.length - 1; // everything but
            // filename...
            first = false;
        } else {
            String[] path = fullFilePath.split("[/\\\\]");
            int pathPrefix = path.length - 1; // everything but
            // filename...
            if (pathPrefix < commonPrefix)
                commonPrefix = pathPrefix;
            for (int i = 0; i < commonPrefix; ++i) {
                if (!commonPath[i].equals(path[i])) {
                    commonPrefix = i;
                    break;
                }
            }
        }
    }

    // and now go back through the attachments, adjusting the filename
    // and building the filename mapping.
    for (MultiPartFormItem e : fileNameList) {
        String fullFilePath = e.getFilename();
        String[] filePath = fullFilePath.split("[/\\\\]");
        StringBuilder b = new StringBuilder();
        first = true;
        // start at the first entry after the common prefix...
        for (int i = commonPrefix; i < filePath.length; ++i) {
            if (!first) {
                b.append("/");
            }
            first = false;
            b.append(filePath[i]);
        }
        // and construct the filename with common directory prefix
        // stripped.
        String fileName = b.toString();
        e.setFilename(fileName);
        if (fileName != null) {
            // TODO: possible bug in ODK collect truncating file extension
            // may need to remove this code after ODK collect is fixed
            int indexOfExtension = fileName.lastIndexOf(".");
            if (indexOfExtension > 0) {
                fileNameWithoutExtensionNameMap.put(fileName.substring(0, indexOfExtension), e);
            }
            fileNameMap.put(fileName, e);
        }
    }
}

From source file:org.openehealth.ipf.platform.camel.lbs.http.process.HttpResourceHandler.java

private ResourceList extractFromMultipart(String subUnit, HttpServletRequest request) throws Exception {
    ResourceList resources = new ResourceList();
    ServletFileUpload upload = new ServletFileUpload(null);
    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        extractFromSinglePart(subUnit, resources, iter);
    }//from w  w  w .j  a  va2s  .  c om

    return resources;
}

From source file:org.operamasks.faces.render.widget.AjaxFileUploadRenderer.java

@SuppressWarnings("unchecked")
private void processUploading(FacesContext context, UIComponent component)
        throws IOException, FileUploadException {
    UploadingMediator uploadingMediator = getUploadingMediator();

    if (!uploadingMediator.canStartUploading(context)) {
        return;/*from  www  .  j a v  a2s. com*/
    } else {
        uploadingMediator.startUploading(context);
    }

    UIForm parentForm = getParentForm(component);

    ServletFileUpload upload = new ServletFileUpload();
    upload.setProgressListener(new FileUploadProgressListener(context));
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

    InputStream input = null;
    try {
        FileItemIterator iter = upload.getItemIterator(request);

        int itemIndex = 0;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            UIFileUpload fileUpload = findFileUploadByFieldName(parentForm, item.getFieldName());

            if (!item.isFormField() && isFieldRequired(fileUpload) && isFieldNull(item)) {
                throw new FacesException(getRequiredFacesMessage(context, fileUpload));
            }

            if (!item.isFormField()) {
                FileUploadItem uploadItem = createFileUploadItem(item, ++itemIndex, fileUpload.getMaxSize());

                if (fileUpload == null)
                    throw new FacesException("Can't find corresponding UIFileUpload component for this field "
                            + uploadItem.getFieldName());

                input = openStream(item, fileUpload);
                if (fileUpload.getWriteTo() != null) {
                    writeToFile(input, fileUpload.getWriteTo());
                } else {
                    fileUpload.getUploadListener().invoke(context.getELContext(), new Object[] { uploadItem });

                    consumeStream(input);
                }
            } else {
                // Only need process file uploading, so consume other form fields
                input = openStream(item, fileUpload);
                consumeStream(input);
            }
        }
    } catch (FileUploadException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        if (input != null)
            input.close();
    }
}