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();

Source Link

Document

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

Usage

From source file:gwtupload.server.UploadServlet.java

private String formFieldToXml(FileItem i) {
    Map<String, String> item = new HashMap<String, String>();
    // CDATA??xml??
    item.put(TAG_VALUE, "<![CDATA[" + i.getString() + "]]>");
    item.put(TAG_FIELD, "" + i.getFieldName());

    Map<String, String> param = new HashMap<String, String>();
    param.put(TAG_PARAM, statusToString(item));
    return statusToString(param);
}

From source file:it.infn.ct.chipster.Chipster.java

public String[] uploadChipsterSettings(ActionRequest actionRequest, ActionResponse actionResponse,
        String username) {/*from   w ww .  j a  va 2  s.c  o  m*/
    String[] CHIPSTER_Parameters = new String[4];
    boolean status;

    // Check that we have a file upload request
    boolean isMultipart = PortletFileUpload.isMultipartContent(actionRequest);

    if (isMultipart) {
        // Create a factory for disk-based file items.
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constrains
        File CHIPSTER_Repository = new File("/tmp");
        if (!CHIPSTER_Repository.exists())
            status = CHIPSTER_Repository.mkdirs();
        factory.setRepository(CHIPSTER_Repository);

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

        try {
            // Parse the request
            List items = upload.parseRequest(actionRequest);
            // Processing items
            Iterator iter = items.iterator();

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();

                DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                //String timeStamp = dateFormat.format(Calendar.getInstance().getTime());

                // Processing a regular form field
                if (item.isFormField()) {
                    //if (fieldName.equals("chipster_login"))                                
                    //        CHIPSTER_Parameters[0]=item.getString();

                    if (fieldName.equals("chipster_password1"))
                        CHIPSTER_Parameters[1] = item.getString();

                }

                if (fieldName.equals("EnableNotification"))
                    CHIPSTER_Parameters[2] = item.getString();

                if (fieldName.equals("chipster_alias"))
                    CHIPSTER_Parameters[3] = item.getString();

            } // end while
        } catch (FileUploadException ex) {
            Logger.getLogger(Chipster.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(Chipster.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return CHIPSTER_Parameters;
}

From source file:com.estampate.corteI.servlet.guardarEstampa.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w  w w.  ja  v  a 2s. c  om*/
 * @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 rutaImg = "NN";
    /*
     SUBIR LA IMAGEN AL SERVIDOR
     */
    dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles"));
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue());
        List listUploadFiles = null;
        FileItem item = null;
        try {
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String extension = nombre.substring(nombre.lastIndexOf("."));
                        File archivo = new File(dirUploadFiles, nombre);
                        item.write(archivo);
                        if (archivo.exists()) {
                            subioImagen = true;
                            rutaImg = "estampas/" + nombre;
                            //                response.sendRedirect("uploadsave.jsp");
                        } else {
                            subioImagen = false;
                        }
                    }
                } else {
                    campos.add(item.getString());
                }
            }
        } catch (FileUploadException e) {
            subioImagen = false;
        } catch (Exception e) {
            subioImagen = false;
        }
    }
    /*
     FIN DE SUBIR IMAGEN
     */
    String nombreImg = campos.get(1);
    EstampaCamiseta estampa = new EstampaCamiseta();
    //estampa.setIdEstampaCamiseta(null);
    //TRAIGO EL ARTISTA PARA GUARDARLO EN LA ESTAMPA
    datosGeneralesDAO artista = new datosGeneralesDAO();
    Artista artEstampa = artista.getArtista(Integer.parseInt(campos.get(0)));
    estampa.setArtista(artEstampa);
    //TRAIGO EL ARTISTA PARA GUARDARLO EN LA ESTAMPA
    datosGeneralesDAO rating = new datosGeneralesDAO();
    RatingEstampa ratingEstampa = rating.getRating(1);
    estampa.setRatingEstampa(ratingEstampa);
    //TRAIGO EL TAMAO QUE ELIGIERON DE LA ESTAMPA
    datosGeneralesDAO tamano = new datosGeneralesDAO();
    TamanoEstampa tamEstampa = tamano.getTamano(Integer.parseInt(campos.get(4)));
    estampa.setTamanoEstampa(tamEstampa);
    //TRAIGO EL TEMA QUE ELIGIERON DE LA ESTAMPA
    datosGeneralesDAO tema = new datosGeneralesDAO();
    TemaEstampa temaEstampa = tema.getTema(Integer.parseInt(campos.get(2)));
    estampa.setTemaEstampa(temaEstampa);
    //ASIGNO EL NOMBRE DE LA ESTAMPA
    estampa.setDescripcion(nombreImg);
    //ASIGNO LA RUTA DE LA IMAGEN QUE CREO
    estampa.setImagenes(rutaImg);
    //ASIGNO LA UBICACION DE LA IMAGEN EN LA CAMISA
    estampa.setUbicacion(campos.get(5));
    //ASIGNO EL PRECIO DE LA IMAGEN QUE CREO
    estampa.setPrecio(campos.get(3));
    //ASIGNO EL ID DEL LUGAR 
    estampa.setIdLugarEstampa(Integer.parseInt(campos.get(5)));
    guardarRegistroDAO guardarEstampa = new guardarRegistroDAO();
    guardarEstampa.guardaEstampa(estampa);
    processRequest(request, response);
}

From source file:hu.sztaki.lpds.pgportal.portlets.asm.ClientError.java

public void doUpload(ActionRequest request, ActionResponse response) throws PortletException {
    try {//from w w  w  .j  a  va 2 s . co m
        String jobport = "";
        String selected_wf = "";
        //getting upload parameters
        ActionRequest temp_req = request;

        DiskFileItemFactory factory = new DiskFileItemFactory();
        PortletFileUpload pfu = new PortletFileUpload(factory);

        List fileItems = pfu.parseRequest(temp_req);

        Iterator iter = fileItems.iterator();
        FileItem file2upload = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            // retrieve hidden parameters if item is a form field
            if (item.isFormField()) {
                if (item.getFieldName().equals(new String("where2upload"))) {
                    jobport = item.getString();
                }
                if (item.getFieldName().startsWith(new String("instance_upload"))) {
                    selected_wf = item.getString();
                }
            } else {
                file2upload = item;
            }
        }

        String[] splitted = jobport.split("@");
        String selected_job = splitted[0];

        String selected_port = splitted[1];

        String userId = request.getRemoteUser();

        File uploadedFile = asm_service.uploadFiletoPortalServer(file2upload, userId, file2upload.getName());
        asm_service.placeUploadedFile(request.getRemoteUser(), uploadedFile, selected_wf, selected_job,
                selected_port);

    } catch (Exception ex) {
        ex.printStackTrace();
        Logger.getLogger(ASM_SamplePortlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.zimbra.cs.service.FileUploadServlet.java

@SuppressWarnings("unchecked")
List<Upload> handleMultipartUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct,
        boolean limitByFileUploadMaxSize, AuthToken at, boolean csrfCheckComplete)
        throws IOException, ServiceException {
    List<FileItem> items = null;
    String reqId = null;//w  w  w  .  j ava  2  s  .  c  o  m

    ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
    try {
        items = upload.parseRequest(req);

        if (!csrfCheckComplete && !CsrfUtil.checkCsrfInMultipartFileUpload(items, at)) {
            drainRequestStream(req);
            mLog.info("CSRF token validation failed for account: %s, Auth token is CSRF enabled",
                    acct.getName());
            sendResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, fmt, null, null, items);
            return Collections.emptyList();
        }
    } catch (FileUploadBase.SizeLimitExceededException e) {
        // at least one file was over max allowed size
        mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, reqId, null, items);
        return Collections.emptyList();
    } catch (FileUploadBase.InvalidContentTypeException e) {
        // at least one file was of a type not allowed
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, fmt, reqId, null, items);
        return Collections.emptyList();
    } catch (FileUploadException e) {
        // parse of request failed for some other reason
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, reqId, null, items);
        return Collections.emptyList();
    }

    String charset = "utf-8";
    LinkedList<String> names = new LinkedList<String>();
    HashMap<FileItem, String> filenames = new HashMap<FileItem, String>();
    if (items != null) {
        for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
            FileItem fi = it.next();
            if (fi == null)
                continue;

            if (fi.isFormField()) {
                if (fi.getFieldName().equals("requestId")) {
                    // correlate this file upload session's request and response
                    reqId = fi.getString();
                } else if (fi.getFieldName().equals("_charset_") && !fi.getString().equals("")) {
                    // get the form value charset, if specified
                    charset = fi.getString();
                } else if (fi.getFieldName().startsWith("filename")) {
                    // allow a client to explicitly provide filenames for the uploads
                    names.clear();
                    String value = fi.getString(charset);
                    if (!Strings.isNullOrEmpty(value)) {
                        for (String name : value.split("\n")) {
                            names.add(name.trim());
                        }
                    }
                }
                // strip form fields out of the list of uploads
                it.remove();
            } else {
                if (fi.getName() == null || fi.getName().trim().equals("")) {
                    it.remove();
                } else {
                    filenames.put(fi, names.isEmpty() ? null : names.remove());
                }
            }
        }
    }

    // restrict requestId value for safety due to later use in javascript
    if (reqId != null && reqId.length() != 0) {
        if (!ALLOWED_REQUESTID_CHARS.matcher(reqId).matches()) {
            mLog.info("Rejecting upload with invalid chars in reqId: %s", reqId);
            sendResponse(resp, HttpServletResponse.SC_BAD_REQUEST, fmt, null, null, items);
            return Collections.emptyList();
        }
    }

    // empty upload is not a "success"
    if (items == null || items.isEmpty()) {
        mLog.info("No data in upload for reqId: %s", reqId);
        sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, reqId, null, items);
        return Collections.emptyList();
    }

    // cache the uploaded files in the hash and construct the list of upload IDs
    List<Upload> uploads = new ArrayList<Upload>(items.size());
    for (FileItem fi : items) {
        String name = filenames.get(fi);
        if (name == null || name.trim().equals(""))
            name = fi.getName();
        Upload up = new Upload(acct.getId(), fi, name);

        mLog.info("Received multipart: %s", up);
        synchronized (mPending) {
            mPending.put(up.uuid, up);
        }
        uploads.add(up);
    }

    sendResponse(resp, HttpServletResponse.SC_OK, fmt, reqId, uploads, items);
    return uploads;
}

From source file:gabi.FileUploadServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  www . ja v  a  2  s  . co 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 Exception {
    System.out.println("inside file upload");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    if (isMultipart) {
        // Create a factory for disk-based file items  
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler  
        ServletFileUpload upload = new ServletFileUpload(factory);
        boolean status = false;
        try {
            // Parse the request  
            List /* FileItem */ items = upload.parseRequest(request);
            Iterator iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String root = getServletContext().getRealPath("/");
                    System.out.println("root path" + root);
                    File path = new File(root + "/uploads");
                    System.out.println("final path" + path);
                    if (!path.exists()) {
                        status = path.mkdirs();
                    }
                    File uploadedFile = new File(path + "/" + fileName);
                    System.out.println(uploadedFile.getAbsolutePath());
                    if (fileName != "") {
                        item.write(uploadedFile);
                        unzip(uploadedFile.getAbsolutePath(), root + "/uploads");
                        out.println("true");
                    } else {
                        System.out.println("File Uploaded Not Successful....");
                    }
                } else {
                    String abc = item.getString();
                    //        out.println("<br><br><h1>"+abc+"</h1><br><br>");  
                }
            }
        } catch (FileUploadException e) {
            System.out.println(e);
        }
    } else {
        out.println("false");
        System.out.println("Not Multipart");
    }
}

From source file:co.estampas.servlets.guardarEstampa.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w ww.j a v a2 s  .  co  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 rutaImg = "NN";
    /*
     SUBIR LA IMAGEN AL SERVIDOR
     */
    dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles"));
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue());
        List listUploadFiles = null;
        FileItem item = null;
        try {
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String extension = nombre.substring(nombre.lastIndexOf("."));
                        File archivo = new File(dirUploadFiles, nombre);
                        item.write(archivo);
                        if (archivo.exists()) {
                            subioImagen = true;
                            rutaImg = "estampas/" + nombre;
                            //                response.sendRedirect("uploadsave.jsp");
                        } else {
                            subioImagen = false;
                        }
                    }
                } else {
                    campos.add(item.getString());
                }
            }
        } catch (FileUploadException e) {
            subioImagen = false;
        } catch (Exception e) {
            subioImagen = false;
        }
    }
    if (subioImagen) {
        String nombreImg = campos.get(1);
        processRequest(request, response);
        EstampaCamiseta estampa = new EstampaCamiseta();
        //BUSCO EL ARTISTA QUE VA A GUARDAR LA ESTAMPA
        this.idArtistax = Integer.parseInt(campos.get(0));
        Artista ar = artistaFacade.find(Integer.parseInt(campos.get(0)));
        estampa.setIdArtista(ar);
        //TRAIGO EL TAMAO QUE ELIGIERON DE LA ESTAMPA
        TamanoEstampa tamEstampa = tamanoEstampaFacade.find(Integer.parseInt(campos.get(4)));
        estampa.setIdTamanoEstampa(tamEstampa);
        //TRAIGO EL TEMA QUE ELIGIERON DE LA ESTAMPA
        TemaEstampa temaEstampa = temaEstampaFacade.find(Integer.parseInt(campos.get(2)));
        estampa.setIdTemaEstampa(temaEstampa);
        //ASIGNO EL NOMBRE DE LA ESTAMPA
        estampa.setDescripcion(nombreImg);
        //ASIGNO LA RUTA DE LA IMAGEN QUE CREO
        estampa.setImagenes(rutaImg);
        //ASIGNO LA UBICACION DE LA IMAGEN EN LA CAMISA
        estampa.setUbicacion(campos.get(5));
        //ASIGNO EL PRECIO DE LA IMAGEN QUE CREO
        estampa.setPrecio(campos.get(3));
        //ASIGNO EL ID DEL LUGAR 
        estampa.setIdLugarEstampa(Integer.parseInt(campos.get(5)));
        //GUARDAR LA ESTAMPA
        estampaCamisetaFacade.create(estampa);
    } else {
        System.out.println("Error al subir imagen");
    }
    campos = new ArrayList<>();

    processRequest(request, response);
}

From source file:gov.nist.appvet.servlet.AppVetServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {

    AppVetServletCommand command = null;
    String commandStr = null;/*from www.  j  a  va 2  s  .  co m*/
    String userName = null;
    String password = null;
    String sessionId = null;
    String toolId = null;
    String toolRisk = null;
    String appId = null;
    FileItem fileItem = null;
    String clientIpAddress = request.getRemoteAddr();
    FileItemFactory factory = null;
    ServletFileUpload upload = null;
    List<FileItem> items = null;
    Iterator<FileItem> iter = null;
    FileItem item = null;

    try {
        factory = new DiskFileItemFactory();
        upload = new ServletFileUpload(factory);
        items = upload.parseRequest(request);
        iter = items.iterator();
        String incomingParameter = null;
        String incomingValue = null;
        while (iter.hasNext()) {
            item = iter.next();
            if (item.isFormField()) {
                incomingParameter = item.getFieldName();
                incomingValue = item.getString();
                if (incomingParameter.equals("command")) {
                    commandStr = incomingValue;
                    log.debug("commandStr: " + commandStr);
                } else if (incomingParameter.equals("username")) {
                    userName = incomingValue;
                    log.debug("userName: " + userName);
                } else if (incomingParameter.equals("password")) {
                    password = incomingValue;
                    log.debug("password: " + password);
                } else if (incomingParameter.equals("sessionid")) {
                    sessionId = incomingValue;
                    log.debug("sessionId: " + sessionId);
                } else if (incomingParameter.equals("toolid")) {
                    toolId = incomingValue;
                    log.debug("toolid: " + toolId);
                } else if (incomingParameter.equals("toolrisk")) {
                    toolRisk = incomingValue;
                    log.debug("toolrisk: " + toolRisk);
                } else if (incomingParameter.equals("appid")) {
                    appId = incomingValue;
                    log.debug("appId: " + appId);
                } else {
                    log.warn("Received unknown parameter: " + incomingValue + " from IP: " + clientIpAddress);
                }
            } else {
                // item should now hold the received file
                fileItem = item;
            }
        }
        incomingParameter = null;
        incomingValue = null;

        //-------------------------- Authenticate --------------------------
        if (isAuthenticated(sessionId, userName, password, clientIpAddress, commandStr)) {
            if (sessionId != null) {
                userName = Database.getSessionUser(sessionId);
            }
        } else {
            sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                    ErrorMessage.AUTHENTICATION_ERROR.getDescription(), response,
                    HttpServletResponse.SC_BAD_REQUEST, true);
            return;
        }

        //--------------------- Verify file attachment ---------------------
        if (fileItem == null) {
            sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                    ErrorMessage.MISSING_FILE.getDescription(), response, HttpServletResponse.SC_BAD_REQUEST,
                    true);
            return;
        }
        if (!ValidateBase.isLegalFileName(fileItem.getName())) {
            sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                    ErrorMessage.ILLEGAL_CHAR_IN_UPLOADED_FILENAME_ERROR.getDescription(), response,
                    HttpServletResponse.SC_BAD_REQUEST, true);
            return;
        }

        //------------------------- Handle command -------------------------
        AppInfo appInfo = null;
        command = AppVetServletCommand.valueOf(commandStr);
        switch (command) {
        case SUBMIT_APP:
            log.debug(userName + " invoked " + command.name() + " with file " + fileItem.getName());
            if (!ValidateBase.hasValidAppFileExtension(fileItem.getName())) {
                sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                        ErrorMessage.INVALID_APP_FILE_EXTENSION.getDescription(), response,
                        HttpServletResponse.SC_BAD_REQUEST, true);
                return;
            } else {
                appInfo = createAppInfo(userName, sessionId, fileItem, clientIpAddress, request);
                if (appInfo == null)
                    return;
                else {
                    sendHttpResponse(userName, appInfo.appId, commandStr, clientIpAddress,
                            "HTTP/1.1 202 Accepted", response, HttpServletResponse.SC_ACCEPTED, false);
                    Registration registration = new Registration(appInfo);
                    registration.registerApp();
                }
            }
            break;
        case SUBMIT_REPORT:
            log.debug(userName + " invoked " + command.name() + " on app " + appId + " with report "
                    + fileItem.getName());
            if (!ValidateBase.hasValidReportFileExtension(fileItem.getName())) {
                sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                        ErrorMessage.INVALID_REPORT_FILE_EXTENSION.getDescription(), response,
                        HttpServletResponse.SC_BAD_REQUEST, true);
                return;
            } else {
                sendHttpResponse(userName, appId, commandStr, clientIpAddress, "HTTP/1.1 202 Accepted",
                        response, HttpServletResponse.SC_ACCEPTED, false);
                appInfo = createAppInfo(appId, userName, commandStr, toolId, toolRisk, fileItem,
                        clientIpAddress, response);
                if (appInfo == null)
                    return;
                else
                    submitReport(userName, appInfo, response);
            }
            break;
        default:
            log.warn("Received unknown command: " + commandStr + " from IP: " + clientIpAddress);
        }
    } catch (final FileUploadException e) {
        sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                ErrorMessage.FILE_UPLOAD_ERROR.getDescription(), response, HttpServletResponse.SC_BAD_REQUEST,
                true);
        return;
    } finally {
        command = null;
        commandStr = null;
        userName = null;
        password = null;
        sessionId = null;
        toolId = null;
        toolRisk = null;
        appId = null;
        fileItem = null;
        clientIpAddress = null;
        factory = null;
        upload = null;
        items = null;
        iter = null;
        item = null;
        System.gc();
    }
}