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

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

Introduction

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

Prototype

String getString(String encoding) throws UnsupportedEncodingException;

Source Link

Document

Returns the contents of the file item as a String, using the specified encoding.

Usage

From source file:com.xpn.xwiki.web.Utils.java

/**
 * Process a multi-part request, extracting all the uploaded files.
 * //from  ww  w.  j  a  va 2 s  .com
 * @param request the current request to process
 * @param context the current context
 * @return the instance of the {@link FileUploadPlugin} used to parse the uploaded files
 */
public static FileUploadPlugin handleMultipart(HttpServletRequest request, XWikiContext context) {
    FileUploadPlugin fileupload = null;
    try {
        if (request instanceof MultipartRequestWrapper) {
            fileupload = new FileUploadPlugin("fileupload", "fileupload", context);
            fileupload.loadFileList(context);
            context.put("fileuploadplugin", fileupload);
            MultipartRequestWrapper mpreq = (MultipartRequestWrapper) request;
            List<FileItem> fileItems = fileupload.getFileItems(context);
            for (FileItem item : fileItems) {
                if (item.isFormField()) {
                    String sName = item.getFieldName();
                    String sValue = item.getString(context.getWiki().getEncoding());
                    mpreq.setParameter(sName, sValue);
                }
            }
        }
    } catch (Exception e) {
        if ((e instanceof XWikiException)
                && (((XWikiException) e).getCode() == XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE)) {
            context.put("exception", e);
        } else {
            e.printStackTrace();
        }
    }
    return fileupload;
}

From source file:de.micromata.genome.gwiki.page.impl.actionbean.CommonMultipartRequest.java

public void addFormField(FileItem item) {
    final String fn = item.getFieldName();
    final String fv;
    try {//from  www .  j a v a 2 s .  co  m
        fv = item.getString("UTF-8");
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }
    if (multipartParams.containsKey(fn) == false) {
        multipartParams.put(fn, new String[] { fv });
    } else {
        String[] ci = multipartParams.get(fn);
        multipartParams.put(fn, (String[]) ArrayUtils.add(ci, fv));
    }
}

From source file:br.com.caelum.vraptor.interceptor.multipart.MultipartItemsProcessor.java

private String getValue(FileItem item) {
    String encoding = request.getCharacterEncoding();
    if (encoding != null && !encoding.equals("")) {
        try {// w ww  . j  av  a 2 s. co m
            return item.getString(encoding);
        } catch (UnsupportedEncodingException e) {
            logger.warn("Request have an invalid encoding. Ignoring it");
        }
    }
    return item.getString();
}

From source file:com.netfinworks.rest.convert.MultiPartFormDataParamConvert.java

public <T> void processFormField(FileItem item, T pojo) {
    try {//from   ww w  .  j  a  va2  s .c  o m
        String value = item.getString(encoding);
        String name = item.getFieldName();
        if (name == null || Magic.EmtpyString.equals(name)) {
            return;
        }
        Class<?> cls = getPropertyClass(pojo.getClass(), name);
        if (cls == null) {
            return;
        }
        IParamConvert paramConvert = classParamConvertRegistry.get(cls.getName());
        Object oldValue = getPropertyValue(pojo, pojo.getClass(), name);
        Object convertedValue = ConvertUtil.addUrlEncodedStringIfArray(oldValue, value, encoding, cls,
                paramConvert == null ? primitiveConvert : paramConvert);
        if (convertedValue != null) {
            BeanUtils.setProperty(pojo, name, convertedValue);
        }

    } catch (IllegalAccessException e) {
        logger.error("can't invoke none-args constructor of a pojo of {}, please check the Pojo",
                pojo.getClass());
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        logger.error("set pojo property error!", e);
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        logger.error("can't convert stream to " + encoding, e);
        throw new RuntimeException(e);
    }
}

From source file:com.es.keyassistant.resolvers.Resolver0004.java

private void assignPropertiesTo(List<FileItem> formItems, DetectionInfo info) {
    HashMap<String, String> params = new HashMap<String, String>();
    for (FileItem formItem : formItems) {
        if (formItem.isFormField()) {
            try {
                params.put(formItem.getFieldName(), formItem.getString("UTF-8"));
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(Resolver0004.class.getName()).log(Level.SEVERE, null, ex);
            }/*w w  w.  j  a va  2 s .  c om*/
        }
    }
    info.setDetectionOSVersion(params.get("androidVersion"));
    info.setDetectionPhoneId(params.get("identity"));
    info.setDetectionPhoneBrand(params.get("brand"));
    info.setDetectionPhoneModel(params.get("module"));
    info.setDetectionResult(ConvertUtility.parseInt(params.get("result"), -1));
    info.setDetectionOS(params.containsKey("os") ? params.get("os") : "Android");
    info.setDetectionDate(new Date());
}

From source file:com.krawler.esp.handlers.FileUploadHandler.java

public HashMap getItems(HttpServletRequest request) throws ServiceException {
    HashMap itemMap = null;//from w  ww  .j  a v  a 2s.c om
    try {
        FileItemFactory factory = new DiskFileItemFactory(4096, new File("/tmp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(10485760);//10 mb
        List fileItems = upload.parseRequest(request);
        Iterator iter = fileItems.iterator();
        itemMap = new HashMap();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                itemMap.put(item.getFieldName(), item.getString("UTF-8"));
            } else {
                itemMap.put(item.getFieldName(), item);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw ServiceException.FAILURE("FileUploadHandler.getItems", e);
    }
    return itemMap;
}

From source file:net.formio.upload.MultipartRequestPreprocessor.java

private void addItemValue(List<String> list, FileItem item) {
    try {//from w  ww. j a  v a2  s.c o m
        list.add(item.getString(defaultEncoding));
    } catch (UnsupportedEncodingException ex) {
        throw new EncodingException(ex.getMessage(), ex);
    }
}

From source file:de.ingrid.portal.forms.ContactForm.java

public void populate(List<FileItem> items) throws UnsupportedEncodingException {
    if (items != null) {
        clearInput();//from   ww w. j  a v a2s  .co m
        for (FileItem item : items) {
            if (item.getFieldName().equals(FIELD_MESSAGE)) {
                setInput(FIELD_MESSAGE, item.getString("UTF-8"));
            } else if (item.getFieldName().equals(FIELD_FIRSTNAME)) {
                setInput(FIELD_FIRSTNAME, item.getString("UTF-8"));
            } else if (item.getFieldName().equals(FIELD_LASTNAME)) {
                setInput(FIELD_LASTNAME, item.getString("UTF-8"));
            } else if (item.getFieldName().equals(FIELD_COMPANY)) {
                setInput(FIELD_COMPANY, item.getString("UTF-8"));
            } else if (item.getFieldName().equals(FIELD_PHONE)) {
                setInput(FIELD_PHONE, item.getString("UTF-8"));
            } else if (item.getFieldName().equals(FIELD_EMAIL)) {
                setInput(FIELD_EMAIL, item.getString("UTF-8"));
            } else if (item.getFieldName().equals(FIELD_ACTIVITY)) {
                setInput(FIELD_ACTIVITY, item.getString());
            } else if (item.getFieldName().equals(FIELD_INTEREST)) {
                setInput(FIELD_INTEREST, item.getString());
            } else if (item.getFieldName().equals(FIELD_NEWSLETTER)) {
                setInput(FIELD_NEWSLETTER, item.getString());
            } else if (item.getFieldName().equals(FIELD_JCAPTCHA)) {
                setInput(FIELD_JCAPTCHA, item.getString());
            }
        }
    }
}

From source file:com.colegiocefas.cefasrrhh.servlets.subirCurriculo.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w  w w .  j  ava 2 s.c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String dui = request.getParameter("dui");
    String nombre = request.getParameter("nombre");
    String especialidad = request.getParameter("especialidad");
    String url = request.getParameter("url");

    //Cdigo para subir pdf del curriculum al servidor
    try {
        List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                if (item.getFieldName().equals("dui"))
                    dui = item.getString("UTF-8");
                if (item.getFieldName().equals("especialidad"))
                    especialidad = item.getString("UTF-8");
                if (item.getFieldName().equals("nombre"))
                    nombre = item.getString("UTF-8");
            } else {
                Date fecha = Calendar.getInstance().getTime();
                SimpleDateFormat formato = new SimpleDateFormat("yyyyMMdd-hhmmss-");
                String nombreImagen = formato.format(fecha);
                nombreImagen += dui;
                //String fileName = item.getName();
                response.setContentType("text/plain");
                response.setCharacterEncoding("UTF-8");
                String realPath = request.getSession().getServletContext().getRealPath("/");
                File fichero = new File(realPath + "documentos/candidatos/", nombreImagen + ".pdf");
                item.write(fichero);
                url = "documentos/candidatos/" + fichero.getName();
            }
        }
        CtrlCEFAS_Candidato ctrlcandidato = new CtrlCEFAS_Candidato();
        ctrlcandidato.guardarCurriculum(dui, nombre, Integer.parseInt(especialidad), url);
        String mensaje = "<div class='alert alert-success' role='alert'>Guardado</div>";
        response.sendRedirect("ingresarcurriculum.jsp");
    } catch (Exception e) {
        //out.write(e.getMessage());
        //JOptionPane.showMessageDialog(null, e.getMessage());
        throw new ServletException("Parsing file upload failed.", e);
    }
}

From source file:hd.controller.AddImageToProductServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w  w. j  av  a 2  s.c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) { //to do

        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);

            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iter = items.iterator();
            Hashtable params = new Hashtable();

            String fileName = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString("UTF-8"));

                } else if (!item.isFormField()) {
                    try {
                        long time = System.currentTimeMillis();
                        String itemName = item.getName();
                        fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1);
                        String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName;
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            String productID = (String) params.get("txtProductId");
            System.out.println(productID);
            String tilte = (String) params.get("newGalleryName");
            String description = (String) params.get("GalleryDescription");
            String url = "images/" + fileName;
            ProductDAO productDao = new ProductDAO();
            ProductPhoto productPhoto = productDao.insertProductPhoto(tilte, description, url, productID);

            response.sendRedirect("MyProductDetailServlet?action=showDetail&txtProductID=" + productID);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}