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

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

Introduction

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

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

From source file:jenkins.plugins.jclouds.credentials.JCloudsUserWithKey.java

private static String getJsonString(final String fileUploadEntry, final String fieldName) {
    if (null != fileUploadEntry) {
        try {//  w  ww.  j  a va2  s .com
            final FileItem fi = Stapler.getCurrentRequest().getFileItem(fileUploadEntry);
            if (null != fi) {
                final String content = new String(fi.get(), StandardCharsets.UTF_8);
                if (null != content && !content.isEmpty()) {
                    final JsonObject jo = new JsonParser().parse(content).getAsJsonObject();
                    final String value = jo.get(fieldName).getAsString();
                    return value;
                }
            }
        } catch (Exception x) {
            LOGGER.warning(x.getMessage());
        }
    }
    return null;
}

From source file:net.ontopia.topicmaps.classify.ClassifyUtils.java

public static ClassifiableContentIF getFileUploadContent(HttpServletRequest request) {
    // Handle file upload
    String contentType = request.getHeader("content-type");
    // out.write("CT: " + contentType + " " + tm + " " + id);
    if (contentType != null && contentType.startsWith("multipart/form-data")) {
        try {/*w ww .  j a  v  a  2  s  .  co m*/
            FileUpload upload = new FileUpload(new DefaultFileItemFactory());
            for (FileItem item : upload.parseRequest(request)) {
                if (item.getSize() > 0) {
                    // ISSUE: could make use of content type if known
                    byte[] content = item.get();
                    ClassifiableContent cc = new ClassifiableContent();
                    String name = item.getName();
                    if (name != null)
                        cc.setIdentifier("fileupload:name:" + name);
                    else
                        cc.setIdentifier("fileupload:field:" + item.getFieldName());
                    cc.setContent(content);
                    return cc;
                }
            }
        } catch (Exception e) {
            throw new OntopiaRuntimeException(e);
        }
    }
    return null;
}

From source file:fr.paris.lutece.plugins.asynchronousupload.util.JSONUtils.java

private static String getPreviewImage(FileItem fileItem) throws IOException {

    if (FileUtil.hasImageExtension(fileItem.getName())) {

        String preview = "data:image/png;base64," + DatatypeConverter.printBase64Binary(fileItem.get());

        return preview;
    }/*from  w  w w  .  j a va 2s .  c  o  m*/

    return StringUtils.EMPTY;
}

From source file:com.tek271.reverseProxy.servlet.ProxyFilter.java

private static MultipartEntity getMultipartEntity(HttpServletRequest request) {
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Enumeration<String> en = request.getParameterNames();
    while (en.hasMoreElements()) {
        String name = en.nextElement();
        String value = request.getParameter(name);
        try {/*from   w  w  w.ja  v  a 2s  .  c o m*/
            if (name.equals("file")) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(10000000);// 10 Mo
                List items = upload.parseRequest(request);
                Iterator itr = items.iterator();
                while (itr.hasNext()) {
                    FileItem item = (FileItem) itr.next();
                    File file = new File(item.getName());
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(item.get());
                    fos.flush();
                    fos.close();
                    entity.addPart(name, new FileBody(file, "application/zip"));
                }
            } else {
                entity.addPart(name, new StringBody(value.toString(), "text/plain", Charset.forName("UTF-8")));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (FileUploadException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (FileNotFoundException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }

    return entity;

}

From source file:it.eng.spagobi.commons.utilities.PortletUtilities.java

/**
 * Gets the first uploaded file from a portlet request. This method creates a new file upload handler, 
 * parses the request, processes the uploaded items and then returns the first file as an
 * <code>UploadedFile</code> object.
 * @param portletRequest The input portlet request
 * @return   The first uploaded file object.
 */// w  ww. j  a va2  s  .co  m
public static UploadedFile getFirstUploadedFile(PortletRequest portletRequest) {
    UploadedFile uploadedFile = null;
    try {

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

        //       Parse the request
        List /* FileItem */ items = upload.parseRequest((ActionRequest) portletRequest);

        //       Process the uploaded items
        Iterator iter = items.iterator();
        boolean endLoop = false;
        while (iter.hasNext() && !endLoop) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                //serviceRequest.setAttribute(item.getFieldName(), item.getString());
            } else {
                uploadedFile = new UploadedFile();
                uploadedFile.setFileContent(item.get());
                uploadedFile.setFieldNameInForm(item.getFieldName());
                uploadedFile.setSizeInBytes(item.getSize());
                uploadedFile.setFileName(item.getName());

                endLoop = true;
            }
        }
    } catch (Exception e) {
        logger.error("Cannot parse multipart request", e);
    }
    return uploadedFile;

}

From source file:eu.impact_project.iif.t2.client.Helper.java

/**
 * Extracts all the form input values from a request object. Taverna
 * workflows are read as strings. Other files are converted to Base64
 * strings.//from   w ww  .  j a v  a 2s  . com
 * 
 * @param request
 *            The request object that will be analyzed
 * @return Map containing all form values and files as strings. The name of
 *         the form is used as the index
 */
public static Map<String, String> parseRequest(HttpServletRequest request) {

    // stores all the strings and encoded files from the html form
    Map<String, String> htmlFormItems = new HashMap<String, String>();
    try {

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

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

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

        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            // a normal string field
            if (item.isFormField()) {

                // put the string items into the map
                htmlFormItems.put(item.getFieldName(), item.getString());

                // uploaded workflow file
            } else if (item.getFieldName().startsWith("file_workflow")) {

                htmlFormItems.put(item.getFieldName(), new String(item.get()));

                // uploaded file
            } else {

                // encode the uploaded file to base64
                String currentAttachment = new String(Base64.encode(item.get()));

                // put the encoded attachment into the map
                htmlFormItems.put(item.getFieldName(), currentAttachment);
            }
        }

    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    return htmlFormItems;
}

From source file:fr.paris.lutece.portal.web.xsl.XslExportJspBean.java

/**
 * Get a file contained in the request from the name of the parameter
 *
 * @param strFileInputName name of the file parameter of the request
 * @param request the request/*from w  w w.jav  a 2s .  c om*/
 * @return file the file contained in the request with the given parameter key
 */
private static File getFileData(String strFileInputName, HttpServletRequest request) {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    FileItem fileItem = multipartRequest.getFile(strFileInputName);

    if ((fileItem != null) && (fileItem.getName() != null) && !EMPTY_STRING.equals(fileItem.getName())) {
        File file = new File();
        PhysicalFile physicalFile = new PhysicalFile();
        physicalFile.setValue(fileItem.get());
        file.setTitle(FileUploadService.getFileNameOnly(fileItem));
        file.setSize((int) fileItem.getSize());
        file.setPhysicalFile(physicalFile);
        file.setMimeType(FileSystemUtil.getMIMEType(FileUploadService.getFileNameOnly(fileItem)));

        return file;
    }

    return null;
}

From source file:com.tern.web.FileData.java

FileData(FileItem item) {
    this.fileName = item.getName();
    this.type = item.getContentType();
    this.data = item.get();

    if (fileName != null) {
        int i = fileName.lastIndexOf("/");
        if (i > 0) {
            fileName = fileName.substring(i + 1);
        } else {/*from   www . j a va 2 s  .c o  m*/
            i = fileName.lastIndexOf("\\");
            if (i > 0) {
                fileName = fileName.substring(i + 1);
            }
        }
    }

    this.item = item;
}

From source file:fi.vm.sade.organisaatio.resource.TempFileResource.java

@GET
@Produces(MediaType.TEXT_PLAIN)//w ww.  j  a v a 2  s.  c o m
@Path("/{img}")
@Secured({ "ROLE_APP_ORGANISAATIOHALLINTA" })
public String getImage(@PathParam("img") String img) {
    LOG.info("getting " + getUser() + img);
    FileItem imgFile = data.get(getUser() + img);
    byte[] imgData = imgFile.get();
    return Base64.byteArrayToBase64(imgData, 0, imgData.length);
}

From source file:com.syrup.ui.UploadConfigurationServlet.java

/**
 * /*  ww w. j ava 2s .  c o m*/
 * 
 * @param req
 *            basic request
 * @param resp
 *            basic resp
 * @throws ServletException
 *             basic
 * @throws IOException
 *             basic
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {
        // Create a new file upload handler
        DiskFileUpload upload = new DiskFileUpload();

        // Parse the request
        List<FileItem> items = upload.parseRequest(req);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {

                byte[] data = item.get();

                // Hmm...parse images?
                Util.saveSuccessMessage("Service definitions uploaded.", req);

            }
        }
    } catch (Exception e) {
        Util.saveErrorMessage("Unable to upload or parse file.", req);
    }

    RequestDispatcher dispatch = req.getRequestDispatcher("/upload.jsp");
    dispatch.forward(req, resp);
}