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

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

Introduction

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

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

From source file:com.bristle.javalib.net.http.MultiPartFormDataParamMap.java

/**************************************************************************
* Parse the specified HTTP request, initializing the map, and calling 
* the specified callback (if not null) for each file (if any) in the 
* streamed HTTP request. //from  w  ww.ja  va 2  s.c  o m
*
*@param request              The HTTP request
*@param callback             The callback class
*@throws FileUploadException When the request is badly formed.
*@throws IOException         When an I/O error occurs reading the request.
*@throws Throwable           When thrown by the callback.
**************************************************************************/
public void parseRequestStream(HttpServletRequest request, FileItemStreamCallBack callback)
        throws FileUploadException, IOException, Throwable {
    if (ServletFileUpload.isMultipartContent(request)) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream fileItemStream = iter.next();
            if (fileItemStream.isFormField()) {
                String strParamName = fileItemStream.getFieldName();
                InputStream streamIn = fileItemStream.openStream();
                String strParamValue = Streams.asString(streamIn);
                put(strParamName, strParamValue);
                // Note: Can't do the following usefully.  The Parameter 
                //       Map of the HTTP Request is effectively readonly.
                //       This does not report an error, but is a no-op.
                // request.getParameterMap().put(strParamName, strParamValue);
            } else {
                if (callback != null) {
                    callback.fullyProcessAFileItemStream(fileItemStream);
                }
            }
        }
    } else {
        putAll(request.getParameterMap());
    }
}

From source file:com.medallia.spider.api.DynamicInputImpl.java

/**
 * Creates a new {@link DynamicInputImpl}
 * @param request from which to read the request parameters
 *//*from w  w w.ja  v a2  s.c om*/
public DynamicInputImpl(HttpServletRequest request) {
    @SuppressWarnings("unchecked")
    Map<String, String[]> reqParams = Maps.newHashMap(request.getParameterMap());
    this.inputParams = reqParams;
    if (ServletFileUpload.isMultipartContent(request)) {
        this.fileUploads = Maps.newHashMap();
        Multimap<String, String> inputParamsWithList = ArrayListMultimap.create();

        ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String fieldName = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    inputParamsWithList.put(fieldName, Streams.asString(stream, Charsets.UTF_8.name()));
                } else {
                    final String filename = item.getName();
                    final byte[] bytes = ByteStreams.toByteArray(stream);
                    fileUploads.put(fieldName, new UploadedFile() {
                        @Override
                        public String getFilename() {
                            return filename;
                        }

                        @Override
                        public byte[] getBytes() {
                            return bytes;
                        }

                        @Override
                        public int getSize() {
                            return bytes.length;
                        }
                    });
                }
            }
            for (Entry<String, Collection<String>> entry : inputParamsWithList.asMap().entrySet()) {
                inputParams.put(entry.getKey(), entry.getValue().toArray(new String[0]));
            }
        } catch (IOException | FileUploadException e) {
            throw new IllegalArgumentException("Failed to parse multipart", e);
        }
    } else {
        this.fileUploads = Collections.emptyMap();
    }
}

From source file:com.vmware.photon.controller.api.frontend.resources.image.ImagesResource.java

private Task parseImageDataFromRequest(HttpServletRequest request) throws InternalException, ExternalException {
    Task task = null;/*from w ww.  ja  v  a 2 s  .  c om*/

    ServletFileUpload fileUpload = new ServletFileUpload();
    FileItemIterator iterator = null;
    InputStream itemStream = null;

    try {
        ImageReplicationType replicationType = null;

        iterator = fileUpload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            itemStream = item.openStream();

            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                switch (fieldName.toUpperCase()) {
                case "IMAGEREPLICATION":
                    replicationType = ImageReplicationType.valueOf(Streams.asString(itemStream).toUpperCase());
                    break;
                default:
                    logger.warn(String.format("The parameter '%s' is unknown in image upload.", fieldName));
                }
            } else {
                if (replicationType == null) {
                    throw new ImageUploadException(
                            "ImageReplicationType is required and should be encoded before image data in the upload request.");
                }

                task = imageFeClient.create(itemStream, item.getName(), replicationType);
            }

            itemStream.close();
            itemStream = null;
        }
    } catch (IllegalArgumentException ex) {
        throw new ImageUploadException("Image upload receives invalid parameter", ex);
    } catch (IOException ex) {
        throw new ImageUploadException("Image upload IOException", ex);
    } catch (FileUploadException ex) {
        throw new ImageUploadException("Image upload FileUploadException", ex);
    } finally {
        flushRequest(iterator, itemStream);
    }

    if (task == null) {
        throw new ImageUploadException("There is no image stream data in the image upload request.");
    }

    return task;
}

From source file:foo.domaintest.http.HttpApiModule.java

@Provides
@Singleton//from  w w  w  .j  av  a  2  s  .  co m
Multimap<String, String> provideParameterMap(@RequestData("queryString") String queryString,
        @RequestData("postBody") Lazy<String> lazyPostBody, @RequestData("charset") String requestCharset,
        FileItemIterator multipartIterator) {
    // Calling request.getParameter() or request.getParameterMap() etc. consumes the POST body. If
    // we got the "postpayload" param we don't want to parse the body, so use only the query params.
    // Note that specifying both "payload" and "postpayload" will result in the "payload" param
    // being honored and the POST body being completely ignored.
    ImmutableMultimap.Builder<String, String> params = new ImmutableMultimap.Builder<>();
    Multimap<String, String> getParams = parseQuery(queryString);
    params.putAll(getParams);
    if (getParams.containsKey("postpayload")) {
        // Treat the POST body as if it was the "payload" param.
        return params.put("payload", nullToEmpty(lazyPostBody.get())).build();
    }
    // No "postpayload" so it's safe to consume the POST body and look for params there.
    if (multipartIterator == null) { // Handle GETs and form-urlencoded POST requests.
        params.putAll(parseQuery(nullToEmpty(lazyPostBody.get())));
    } else { // Handle multipart/form-data requests.
        try {
            while (multipartIterator != null && multipartIterator.hasNext()) {
                FileItemStream item = multipartIterator.next();
                try (InputStream stream = item.openStream()) {
                    params.put(item.isFormField() ? item.getFieldName() : item.getName(),
                            CharStreams.toString(new InputStreamReader(stream, requestCharset)));
                }
            }
        } catch (FileUploadException | IOException e) {
            // Ignore the failure and fall through to return whatever params we managed to parse.
        }
    }
    return params.build();
}

From source file:fi.jyu.student.jatahama.onlineinquirytool.server.LoadSaveServlet.java

@Override
public final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {//from www.  j  a v  a  2s.com
        // We always return xhtml in utf-8
        response.setContentType("application/xhtml+xml");
        response.setCharacterEncoding("utf-8");

        // Default filename just in case none is found in form
        String filename = defaultFilename;

        // Commons file upload
        ServletFileUpload upload = new ServletFileUpload();

        // Go through upload items
        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                // Parse form fields
                String fieldname = item.getFieldName();

                if ("chartFilename".equals(fieldname)) {
                    // Ordering is important in client page! We expect filename BEFORE data. Otherwise filename will be default
                    // See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4
                    //   "The parts are sent to the processing agent in the same order the
                    //    corresponding controls appear in the document stream."
                    filename = Streams.asString(stream, "utf-8");
                } else if ("chartDataXML".equals(fieldname)) {
                    log.info("Doing form bounce");
                    String filenameAscii = formSafeAscii(filename);
                    String fileNameUtf = formSafeUtfName(filename);
                    String cdh = "attachment; filename=\"" + filenameAscii + "\"; filename*=utf-8''"
                            + fileNameUtf;
                    response.setHeader("Content-Disposition", cdh);
                    ServletOutputStream out = response.getOutputStream();
                    Streams.copy(stream, out, false);
                    out.flush();
                    // No more processing needed (prevent BOTH form AND upload from happening)
                    return;
                }
            } else {
                // Handle upload
                log.info("Doing file bounce");
                ServletOutputStream out = response.getOutputStream();
                Streams.copy(stream, out, false);
                out.flush();
                // No more processing needed (prevent BOTH form AND upload from happening)
                return;
            }
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

From source file:com.github.davidcarboni.encryptedfileupload.SizesTest.java

@Test
public void testMaxSizeLimitUnknownContentLength() throws IOException, FileUploadException {
    final String request = "-----1234\r\n"
            + "Content-Disposition: form-data; name=\"file1\"; filename=\"foo1.tab\"\r\n"
            + "Content-Type: text/whatever\r\n" + "Content-Length: 10\r\n" + "\r\n"
            + "This is the content of the file\n" + "\r\n" + "-----1234\r\n"
            + "Content-Disposition: form-data; name=\"file2\"; filename=\"foo2.tab\"\r\n"
            + "Content-Type: text/whatever\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n"
            + "-----1234--\r\n";

    ServletFileUpload upload = new ServletFileUpload(new EncryptedFileItemFactory());
    upload.setFileSizeMax(-1);/*from   ww w. j a va  2  s . co  m*/
    upload.setSizeMax(300);

    // the first item should be within the max size limit
    // set the read limit to 10 to simulate a "real" stream
    // otherwise the buffer would be immediately filled

    MockHttpServletRequest req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE);
    req.setContentLength(-1);
    req.setReadLimit(10);

    FileItemIterator it = upload.getItemIterator(req);
    assertTrue(it.hasNext());

    FileItemStream item = it.next();
    assertFalse(item.isFormField());
    assertEquals("file1", item.getFieldName());
    assertEquals("foo1.tab", item.getName());

    {
        @SuppressWarnings("resource") // Streams.copy closes the input file
        InputStream stream = item.openStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Streams.copy(stream, baos, true);
    }

    // the second item is over the size max, thus we expect an error
    try {
        // the header is still within size max -> this shall still succeed
        assertTrue(it.hasNext());
    } catch (Exception e) {
        // FileUploadBase.SizeException has protected access:
        if (e.getClass().getSimpleName().equals("SizeException")) {
            fail();
        } else {
            throw e;
        }
    }

    item = it.next();

    try {
        @SuppressWarnings("resource") // Streams.copy closes the input file
        InputStream stream = item.openStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Streams.copy(stream, baos, true);
        fail();
    } catch (FileUploadIOException e) {
        // expected
    }

}

From source file:ca.nrc.cadc.rest.SyncInput.java

private void processMultiPart(FileItemIterator itemIterator)
        throws FileUploadException, IOException, ResourceNotFoundException {
    while (itemIterator.hasNext()) {
        FileItemStream item = itemIterator.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField())
            processParameter(name, new String[] { Streams.asString(stream) });
        else//  w w  w.java2 s .c om
            processStream(name, item.getContentType(), stream);
    }
}

From source file:com.doculibre.constellio.feedprotocol.FeedServlet.java

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

    LOG.fine("FeedServlet: doPost(...)");
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    PrintWriter out = null;//from  www. java 2  s .co m
    try {
        out = response.getWriter();
        if (isMultipart) {
            ServletFileUpload upload = new ServletFileUpload();

            String datasource = null;
            String feedtype = null;

            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                //Disabled to allow easier update from HTML forms
                //if (item.isFormField()) {
                if (item.getFieldName().equals(FeedParser.XML_DATASOURCE)) {
                    InputStream itemStream = null;
                    try {
                        itemStream = item.openStream();
                        datasource = IOUtils.toString(itemStream);
                    } finally {
                        IOUtils.closeQuietly(itemStream);
                    }
                } else if (item.getFieldName().equals(FeedParser.XML_FEEDTYPE)) {
                    InputStream itemStream = null;
                    try {
                        itemStream = item.openStream();
                        feedtype = IOUtils.toString(itemStream);
                    } finally {
                        IOUtils.closeQuietly(itemStream);
                    }
                } else if (item.getFieldName().equals(FeedParser.XML_DATA)) {
                    try {
                        if (StringUtils.isBlank(datasource)) {
                            throw new IllegalArgumentException("Datasource is blank");
                        }
                        if (StringUtils.isBlank(feedtype)) {
                            throw new IllegalArgumentException("Feedtype is blank");
                        }

                        InputStream contentStream = null;
                        try {
                            contentStream = item.openStream();
                            final Feed feed = new FeedStaxParser().parse(datasource, feedtype, contentStream);

                            Callable<Object> processFeedTask = new Callable<Object>() {
                                @Override
                                public Object call() throws Exception {
                                    FeedProcessor feedProcessor = new FeedProcessor(feed);
                                    feedProcessor.processFeed();
                                    return null;
                                }
                            };
                            threadPoolExecutor.submit(processFeedTask);

                            out.append(GsaFeedConnection.SUCCESS_RESPONSE);
                            return;
                        } catch (Exception e) {
                            LOG.log(Level.SEVERE, "Exception while processing contentStream", e);
                        } finally {
                            IOUtils.closeQuietly(contentStream);
                        }
                    } finally {
                        IOUtils.closeQuietly(out);
                    }
                }
                //}
            }
        }
    } catch (Throwable e) {
        LOG.log(Level.SEVERE, "Exception while uploading", e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    out.append(GsaFeedConnection.INTERNAL_ERROR_RESPONSE);
}

From source file:br.com.ifpb.bdnc.projeto.geo.servlets.CadastraImagem.java

private Image mountImage(HttpServletRequest request) {
    Image image = new Image();
    image.setCoord(new Coordenate());
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {//from  ww  w.j  ava  2  s .  co m
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    InputStream in = item.openStream();
                    byte[] b = new byte[in.available()];
                    in.read(b);
                    if (item.getFieldName().equals("description")) {
                        image.setDescription(new String(b));
                    } else if (item.getFieldName().equals("authors")) {
                        image.setAuthors(new String(b));
                    } else if (item.getFieldName().equals("end")) {
                        image.setDate(
                                LocalDate.parse(new String(b), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    } else if (item.getFieldName().equals("latitude")) {
                        image.getCoord().setLat(new String(b));
                    } else if (item.getFieldName().equals("longitude")) {
                        image.getCoord().setLng(new String(b));
                    } else if (item.getFieldName().equals("heading")) {
                        image.getCoord().setHeading(new String(b));
                    } else if (item.getFieldName().equals("pitch")) {
                        image.getCoord().setPitch(new String(b));
                    } else if (item.getFieldName().equals("zoom")) {
                        image.getCoord().setZoom(new String(b));
                    }
                } else {
                    if (!item.getName().equals("")) {
                        MultipartData md = new MultipartData();
                        String folder = "historicImages";
                        md.setFolder(folder);
                        String path = request.getServletContext().getRealPath("/");
                        System.out.println(path);
                        String nameToSave = "pubImage" + Calendar.getInstance().getTimeInMillis()
                                + item.getName();
                        image.setImagePath(folder + "/" + nameToSave);
                        md.saveImage(path, item, nameToSave);
                        String imageMinPath = folder + "/" + "min" + nameToSave;
                        RedimencionadorImagem.resize(path, folder + "/" + nameToSave,
                                path + "/" + imageMinPath.toString(), IMAGE_MIN_WIDTH, IMAGE_MIM_HEIGHT);
                        image.setMinImagePath(imageMinPath);
                    }
                }
            }
        } catch (FileUploadException | IOException ex) {
            System.out.println("Erro ao manipular dados");
        }
    }
    return image;
}

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

protected void upload(final FileItemIterator fileItemIterator)
        throws IOException, IllegalArgumentException, NodeNotFoundException, NodeAlreadyExistsException {
    boolean inheritParentPermissions = false;
    VOSURI newNodeURI = null;/*w ww.  j  av  a2 s. c  o  m*/

    try {
        while (fileItemIterator.hasNext()) {
            final FileItemStream nextFileItemStream = fileItemIterator.next();

            if (nextFileItemStream.getFieldName().startsWith(UPLOAD_FILE_KEY)) {
                newNodeURI = upload(nextFileItemStream);

            } else if (nextFileItemStream.getFieldName().equals("inheritPermissionsCheckBox")) {
                inheritParentPermissions = true;
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }

    if (inheritParentPermissions) {
        setInheritedPermissions(newNodeURI);
    }
}