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

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

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem 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:Controlador.Contr_Seleccion.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww w . j ava  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 {
    /*Se detalla el contenido que tendra el servlet*/
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    /*Se crea una variable para la sesion*/
    HttpSession session = request.getSession(true);

    boolean b;
    try {
        /*Se declaran las variables necesarias*/
        Cls_Seleccion sel = new Cls_Seleccion();
        String Codigo = "", Mensaje = "", Nombre = "", Tipo = "", Imagen = "", url, Peti;
        String urlsalidaimg;
        urlsalidaimg = "/media/santiago/Santiago/IMGTE/";
        //urlsalidaimg = "D:\\IMGTE\\";
        String urlimgservidor = this.getServletContext().getRealPath("/Libs/Customs/images/Seleccion");
        /*FileItemFactory es una interfaz para crear FileItem*/
        FileItemFactory file_factory = new DiskFileItemFactory();

        /*ServletFileUpload esta clase convierte los input file a FileItem*/
        ServletFileUpload servlet_up = new ServletFileUpload(file_factory);
        /*sacando los FileItem del ServletFileUpload en una lista */
        servlet_up.setHeaderEncoding("UTF-8");
        List items = servlet_up.parseRequest(request);
        Iterator it = items.iterator();

        /*Se evalua cada una de las posibles peticiones y los posibles campos que envien*/
        while (it.hasNext()) {
            FileItem item = (FileItem) it.next();
            if (item.isFormField()) {
                //Plain request parameters will come here. 

                String name = item.getFieldName();
                if (name.equals("Codigo")) {
                    /*Se guarda el campo en la clase*/
                    sel.setCodigo(item.getString());
                } else if (name.equals("Nombre")) {
                    /**
                     * Se guarda el campo en la clase
                     */
                    sel.setNombre(item.getString());
                } else if (name.equals("Tipo")) {
                    /**
                     * Se guarda el campo en la clase
                     */
                    sel.setTipo(item.getString());
                } else if (name.equals("Estado")) {
                    /**
                     * Se guarda el campo en la clase
                     */
                    sel.setEstado(item.getString());
                } else if (name.equals("RegistrarSeleccion")) {
                    /*Se evalua si se mando una iamgen, cuando se va a registrar un evento*/
                    if (!sel.getImagen().equals("")) {
                        /*Si se envia una imagen obtiene la imagen para guardarla en el server luego*/
                        File img = new File(sel.getImagen());
                        /*Se ejecuta el metodo de registrar usuario que se encuentra, en la clase modelo
                         con los datos que se encuentran en la clase*/

                        b = sel.setRegistrarSeleccion(sel.getNombre(), sel.getTipo(), sel.getTypeImg());
                        if (b) {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            File imagedb = new File(urlimgservidor + "/" + sel.getCodigo() + sel.getTypeImg());
                            img.renameTo(imagedb);
                            session.setAttribute("Mensaje",
                                    "El gusto o ambiente ha sido registrado correctamente.");
                            session.setAttribute("TipoMensaje", "Dio");
                            url = "View/ConsultaSeleccion.jsp";
                            response.sendRedirect(url);
                        } else {
                            img.delete();
                            /*Se guarda un mensaje de error mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje", sel.getMensaje());
                            session.setAttribute("TipoMensaje", "NODio");
                            url = "View/ConsultaSeleccion.jsp";
                            response.sendRedirect(url);
                        }
                    } else {
                        /*Se guarda un mensaje de error mediante las sesiones
                         y se redirecciona*/
                        session.setAttribute("Mensaje",
                                "Seleccione una imagen, para registrar el ambiente o gusto.");
                        session.setAttribute("TipoMensaje", "NODio");
                    }
                } else if (name.equals("ModificarSeleccion")) {
                    if (sel.getImagen().equals("")) {
                        /*Se ejecuta el metodo de actualizar los datos de la seleccion usuario que se encuentra, en la clase modelo
                         con los datos que se encuentran en la clase*/
                        b = sel.actualizardatosSeleccion(sel.getCodigo(), sel.getNombre(), sel.getTipo(),
                                sel.getEstado());
                        if (b) {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "El gusto o ambiente ha sido registrada correctamente.");
                            session.setAttribute("TipoMensaje", "Dio");
                            url = "View/ConsultaSeleccion.jsp";
                            response.sendRedirect(url);
                        } else {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje", sel.getMensaje());
                            session.setAttribute("TipoMensaje", "NODio");
                            url = "View/ConsultaSeleccion.jsp";
                            response.sendRedirect(url);
                        }
                    } else {
                        /*Se ejecuta el metodo de actualizar los datos de la seleccion usuario que se encuentra, en la clase modelo
                         con los datos que se encuentran en la clase*/
                        File img = new File(sel.getImagen());
                        b = sel.actualizardatosSeleccion(sel.getCodigo(), sel.getNombre(), sel.getTipo(),
                                sel.getTypeImg(), sel.getEstado());
                        if (b) {
                            File imagedb = new File(urlimgservidor + "/" + sel.getCodigo() + sel.getTypeImg());
                            img.renameTo(imagedb);
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "El gusto o ambiente ha sido modificado correctamente.");
                            session.setAttribute("TipoMensaje", "Dio");
                            url = "View/ConsultaSeleccion.jsp";
                            response.sendRedirect(url);
                        } else {
                            img.delete();
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje", sel.getMensaje());
                            session.setAttribute("TipoMensaje", "NODio");
                            url = "View/ConsultaSeleccion.jsp";
                            response.sendRedirect(url);
                        }
                    }
                }

            } else {
                if (!item.getName().equals("")) {
                    //uploaded files will come here.
                    FileItem file = item;
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();

                    if (sizeInBytes > 1000000) {
                        /*Se muestra un mensaje en caso de pesar mas de 3 MB*/
                        session.setAttribute("Mensaje", "El tamao lmite de la imagen es: 1 MB");
                        session.setAttribute("TipoMensaje", "NODio");
                        /*Se redirecciona*/
                        response.sendRedirect("View/ConsultaSeleccion.jsp");
                    } else {
                        if (contentType.indexOf("jpeg") > 0 || contentType.indexOf("png") > 0) {
                            if (contentType.indexOf("jpeg") > 0) {
                                contentType = ".jpg";
                            } else {
                                contentType = ".png";
                            }
                            /*Se crea la imagne*/
                            File archivo_server = new File(urlimgservidor + "/" + item.getName());
                            /*Se guardael nombre y tipo de imagen en la clase*/
                            sel.setImagen(urlimgservidor + "/" + item.getName());
                            sel.setTypeImg(contentType);
                            /*Se guarda la imagen*/
                            item.write(archivo_server);
                        } else {
                            session.setAttribute("Mensaje", "Solo se pueden registrar imagenes JPG o PNG");
                            session.setAttribute("TipoMensaje", "NODio");
                        }
                    }
                } else {
                    /*Se guarda el url de la imagen en la clase*/
                    sel.setImagen("");
                }
            }
        }

        /*Se redirecciona sino se recive ninguna peticion*/
        response.sendRedirect("View/index.jsp");
    } catch (FileUploadException ex) {
        /*Se muestra un mensaje en caso de error*/
        System.out.print(ex.getMessage().toString());
    } catch (Exception ex) {
        /*Se muestra un mensaje en caso de error*/
        Logger.getLogger(Contr_Seleccion.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.trsst.ui.AppServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // FLAG: limit access only to local clients
    if (restricted && !request.getRemoteAddr().equals(request.getLocalAddr())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Non-local clients are not allowed.");
        return;//from   ww w  .jav a2  s .c  om
    }

    // in case of any posted files
    InputStream inStream = null;

    // determine if supported command: pull, push, post
    String path = request.getPathInfo();
    System.err.println(new Date().toString() + " " + path);
    if (path != null) {
        // FLAG: limit only to pull and post
        if (path.startsWith("/pull/") || path.startsWith("/post")) {
            // FLAG: we're sending the user's keystore
            // password over the wire (over SSL)
            List<String> args = new LinkedList<String>();
            if (path.startsWith("/pull/")) {
                path = path.substring("/pull/".length());
                response.setContentType("application/atom+xml; type=feed; charset=utf-8");
                // System.out.println("doPull: " +
                // request.getParameterMap());
                args.add("pull");
                if (request.getParameterMap().size() > 0) {
                    boolean first = true;
                    for (Object name : request.getParameterMap().keySet()) {
                        // FLAG: don't allow "home" (server-abuse)
                        // FLAG: don't allow "attach" (file-system access)
                        if ("decrypt".equals(name) || "pass".equals(name)) {
                            for (String value : request.getParameterValues(name.toString())) {
                                args.add("--" + name.toString());
                                args.add(value);
                            }
                        } else {
                            for (String value : request.getParameterValues(name.toString())) {
                                if (first) {
                                    path = path + '?';
                                    first = false;
                                } else {
                                    path = path + '&';
                                }
                                path = path + name + '=' + value;
                            }
                        }
                    }
                }
                args.add(path);

            } else if (path.startsWith("/post")) {
                // System.out.println("doPost: " +
                // request.getParameterMap());
                args.add("post");

                try { // h/t http://stackoverflow.com/questions/2422468
                    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory())
                            .parseRequest(request);
                    for (FileItem item : items) {
                        if (item.isFormField()) {
                            // process regular form field
                            String name = item.getFieldName();
                            String value = item.getString("UTF-8").trim();
                            // System.out.println("AppServlet: " + name
                            // + " : " + value);
                            if (value.length() > 0) {
                                // FLAG: don't allow "home" (server-abuse)
                                // FLAG: don't allow "attach" (file-system
                                // access)
                                if ("id".equals(name)) {
                                    if (value.startsWith("urn:feed:")) {
                                        value = value.substring("urn:feed:".length());
                                    }
                                    args.add(value);
                                } else if (!"home".equals(name) && !"attach".equals(name)) {
                                    args.add("--" + name);
                                    args.add(value);
                                }
                            } else {
                                log.debug("Empty form value for name: " + name);
                            }
                        } else if (item.getSize() > 0) {
                            // process form file field (input type="file").
                            // String filename = FilenameUtils.getName(item
                            // .getName());
                            if (item.getSize() > 1024 * 1024 * 10) {
                                throw new FileUploadException("Current maximum upload size is 10MB");
                            }
                            String name = item.getFieldName();
                            if ("icon".equals(name) || "logo".equals(name)) {
                                args.add("--" + name);
                                args.add("-");
                            }
                            inStream = item.getInputStream();
                            // NOTE: only handles one file!
                        } else {
                            log.debug("Ignored form field: " + item.getFieldName());
                        }
                    }
                } catch (FileUploadException e) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                            "Could not parse multipart request: " + e);
                    return;
                }
            }

            // send post data if any to command input stream
            if (inStream != null) {
                args.add("--attach");
            }
            //System.out.println(args);

            // make sure we don't create another local server
            args.add("--host");
            args.add(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + "/feed");

            PrintStream outStream = new PrintStream(response.getOutputStream(), false, "UTF-8");
            int result = new Command().doBegin(args.toArray(new String[0]), outStream, inStream);
            if (result != 0) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Internal error code: " + result);
            } else {
                outStream.flush();
            }
            return;
        }

        // otherwise: determine if static resource request
        if (path.startsWith("/")) {
            path = path.substring(1);
        }

        byte[] result = resources.get(path);
        String mimetype = null;
        if (result == null) {
            // if ("".equals(path) || path.endsWith(".html")) {
            // treat all html requests with index doc
            result = resources.get("index.html");
            mimetype = "text/html";
            // }
        }
        if (result != null) {
            if (mimetype == null) {
                if (path.endsWith(".html")) {
                    mimetype = "text/html";
                } else if (path.endsWith(".css")) {
                    mimetype = "text/css";
                } else if (path.endsWith(".js")) {
                    mimetype = "application/javascript";
                } else if (path.endsWith(".png")) {
                    mimetype = "image/png";
                } else if (path.endsWith(".jpg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".jpeg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".gif")) {
                    mimetype = "image/gif";
                } else {
                    mimetype = new Tika().detect(result);
                }
            }
            if (request.getHeader("If-None-Match:") != null) {
                // client should always use cached version
                log.info("sending 304");
                response.setStatus(304); // Not Modified
                return;
            }
            // otherwise allow ETag/If-None-Match
            response.setHeader("ETag", Long.toHexString(path.hashCode()));
            if (mimetype != null) {
                response.setContentType(mimetype);
            }
            response.setContentLength(result.length);
            response.getOutputStream().write(result);
            return;
        }

    }

    // // otherwise: 404 Not Found
    // response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

From source file:eu.impact_project.wsclient.SOAPresults.java

/**
 * Loads the user values/files and sends them to the web service. Files are
 * encoded to Base64. Stores the resulting message in the session and the
 * resulting files on the server./*from   w w  w . j a  v  a 2s.  c om*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    OutputStream outStream = null;
    BufferedInputStream bis = null;
    user = request.getParameter("user");
    pass = request.getParameter("pass");

    try {

        HttpSession session = request.getSession(true);

        String folder = session.getServletContext().getRealPath("/");
        if (!folder.endsWith("/")) {
            folder = folder + "/";
        }

        Properties props = new Properties();
        InputStream stream = new URL("file:" + folder + "config.properties").openStream();

        props.load(stream);
        stream.close();

        boolean loadDefault = Boolean.parseBoolean(props.getProperty("loadDefaultWebService"));
        boolean supportFileUpload = Boolean.parseBoolean(props.getProperty("supportFileUpload"));
        boolean oneResultFile = Boolean.parseBoolean(props.getProperty("oneResultFile"));
        String defaultFilePrefix = props.getProperty("defaultFilePrefix");

        SoapService serviceObject = (SoapService) session.getAttribute("serviceObject");
        SoapOperation operation = null;
        if (supportFileUpload) {

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

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List /* FileItem */ 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()) {
                    htmlFormItems.put(item.getFieldName(), item.getString());

                    // uploaded file
                } else {

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

                    htmlFormItems.put(item.getFieldName(), currentAttachment);
                }
            }

            // get the chosen WSDL operation
            String operationName = htmlFormItems.get("operationName");

            operation = serviceObject.getOperation(operationName);
            for (SoapInput input : operation.getInputs()) {
                input.setValue(htmlFormItems.get(input.getName()));
            }

        } else {
            // get the chosen WSDL operation
            String operationName = request.getParameter("operationName");

            operation = serviceObject.getOperation(operationName);
            for (SoapInput input : operation.getInputs()) {
                String[] soapInputValues = request.getParameterValues(input.getName());
                input.clearValues();
                for (String value : soapInputValues) {
                    input.addValue(value);
                }
            }

        }

        List<SoapOutput> outs = operation.execute(user, pass);
        String soapResponse = operation.getResponse();

        String htmlResponse = useXslt(soapResponse, "/SoapToHtml.xsl");

        session.setAttribute("htmlResponse", htmlResponse);
        session.setAttribute("soapResponse", soapResponse);

        // for giving the file names back to the JSP
        List<String> fileNames = new ArrayList<String>();

        // process possible attachments in the response
        List<SoapAttachment> attachments = operation.getReceivedAttachments();
        int i = 0;
        for (SoapAttachment attachment : attachments) {

            // path to the server directory
            String serverPath = getServletContext().getRealPath("/");
            if (!serverPath.endsWith("/")) {
                serverPath = folder + "/";
            }

            // construct the file name for the attachment
            String fileEnding = "";
            String contentType = attachment.getContentType();
            System.out.println("content type: " + contentType);
            if (contentType.equals("image/gif")) {
                fileEnding = ".gif";
            } else if (contentType.equals("image/jpeg")) {
                fileEnding = ".jpg";
            } else if (contentType.equals("image/tiff")) {
                fileEnding = ".tif";
            } else if (contentType.equals("application/vnd.ms-excel")) {
                fileEnding = ".xlsx";
            }

            String fileName = loadDefault ? defaultFilePrefix : "attachedFile";

            String counter = oneResultFile ? "" : i + "";

            String attachedFileName = fileName + counter + fileEnding;

            // store the attachment into the file
            File file = new File(serverPath + attachedFileName);
            outStream = new FileOutputStream(file);

            InputStream inStream = attachment.getInputStream();

            bis = new BufferedInputStream(inStream);

            int bufSize = 1024 * 8;

            byte[] bytes = new byte[bufSize];

            int count = bis.read(bytes);
            while (count != -1 && count <= bufSize) {
                outStream.write(bytes, 0, count);
                count = bis.read(bytes);
            }
            if (count != -1) {
                outStream.write(bytes, 0, count);
            }
            outStream.close();
            bis.close();

            fileNames.add(attachedFileName);
            i++;
        }

        // pass the file names to JSP
        request.setAttribute("fileNames", fileNames);

        request.setAttribute("round3", "round3");
        // get back to JSP
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/interface.jsp");
        rd.forward(request, response);

    } catch (Exception e) {
        logger.error("Exception", e);
        e.printStackTrace();
    } finally {
        if (outStream != null) {
            outStream.close();
        }
        if (bis != null) {
            bis.close();
        }
    }

}

From source file:com.liferay.portal.editor.fckeditor.receiver.impl.BaseCommandReceiver.java

public void fileUpload(CommandArgument commandArgument, HttpServletRequest request,
        HttpServletResponse response) {//from  w w w  . j a  v a 2s . c o  m

    InputStream inputStream = null;

    String returnValue = null;

    try {
        ServletFileUpload servletFileUpload = new LiferayFileUpload(
                new LiferayFileItemFactory(UploadServletRequestImpl.getTempDir()), request);

        servletFileUpload
                .setFileSizeMax(PrefsPropsUtil.getLong(PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE));

        LiferayServletRequest liferayServletRequest = new LiferayServletRequest(request);

        List<FileItem> fileItems = servletFileUpload.parseRequest(liferayServletRequest);

        Map<String, Object> fields = new HashMap<String, Object>();

        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {
                fields.put(fileItem.getFieldName(), fileItem.getString());
            } else {
                fields.put(fileItem.getFieldName(), fileItem);
            }
        }

        DiskFileItem diskFileItem = (DiskFileItem) fields.get("NewFile");

        String fileName = StringUtil.replace(diskFileItem.getName(), CharPool.BACK_SLASH, CharPool.SLASH);
        String[] fileNameArray = StringUtil.split(fileName, '/');
        fileName = fileNameArray[fileNameArray.length - 1];

        String contentType = diskFileItem.getContentType();

        if (Validator.isNull(contentType) || contentType.equals(ContentTypes.APPLICATION_OCTET_STREAM)) {

            contentType = MimeTypesUtil.getContentType(diskFileItem.getStoreLocation());
        }

        if (diskFileItem.isInMemory()) {
            inputStream = diskFileItem.getInputStream();
        } else {
            inputStream = new ByteArrayFileInputStream(diskFileItem.getStoreLocation(),
                    LiferayFileItem.THRESHOLD_SIZE);
        }

        long size = diskFileItem.getSize();

        returnValue = fileUpload(commandArgument, fileName, inputStream, contentType, size);
    } catch (Exception e) {
        FCKException fcke = null;

        if (e instanceof FCKException) {
            fcke = (FCKException) e;
        } else {
            fcke = new FCKException(e);
        }

        Throwable cause = fcke.getCause();

        returnValue = "203";

        if (cause != null) {
            String causeString = GetterUtil.getString(cause.toString());

            if (causeString.contains("NoSuchFolderException") || causeString.contains("NoSuchGroupException")) {

                returnValue = "204";
            } else if (causeString.contains("ImageNameException")) {
                returnValue = "205";
            } else if (causeString.contains("FileExtensionException")
                    || causeString.contains("FileNameException")) {

                returnValue = "206";
            } else if (causeString.contains("PrincipalException")) {
                returnValue = "207";
            } else if (causeString.contains("ImageSizeException")
                    || causeString.contains("FileSizeException")) {

                returnValue = "208";
            } else if (causeString.contains("SystemException")) {
                returnValue = "209";
            } else {
                throw fcke;
            }
        }

        _writeUploadResponse(returnValue, response);
    } finally {
        StreamUtil.cleanUp(inputStream);
    }

    _writeUploadResponse(returnValue, response);
}

From source file:com.fatih.edu.tr.NewTaskServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

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

    if (!isMultipart) {
        return;//from w ww.j  ava 2s  .c o m
    }

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

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

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

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);

    TaskDao taskDao = new TaskDao();
    String title = "";
    String description = "";
    String due_date = "";
    String fileName = "";
    String filePath = "";
    //taskDao.addTask(title, description, due_date, "testfile","testdizi",1);

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

            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                fileName = new File(item.getName()).getName();
                filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                item.write(uploadedFile);
            } else {
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();
                if (fieldname.equals("title")) {
                    title = item.getString();
                } else if (fieldname.equals("description")) {
                    description = item.getString();

                } else if (fieldname.equals("due_date")) {
                    due_date = item.getString();
                } else {
                    System.out.println("Something goes wrong in form");
                }
            }

        }
        taskDao.addTask(title, description, due_date, fileName, filePath, 1);
        // displays done.jsp page after upload finished
        getServletContext().getRequestDispatcher("/done.jsp").forward(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:egovframework.com.cmm.web.EgovMultipartResolver.java

/**
 * multipart?  parsing? .//from   w  w w. java 2s  .co  m
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {

    //? 3.0  
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    // Extract multipart files and multipart parameters.
    for (Iterator it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);

                //? 3.0 ? API? 
                List<MultipartFile> fileList = new ArrayList<MultipartFile>();
                fileList.add(file);

                if (multipartFiles.put(fileItem.getName(), fileList) != null) { // CHANGED!!
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                            + file.getStorageDescription());
                }
            }

        }
    }

    return new MultipartParsingResult(multipartFiles, multipartParameters, null);
}

From source file:bijian.util.upload.MyMultiPartRequest.java

private void processFileField(FileItem item) {
    LOG.debug("Item is a file upload");

    // Skip file uploads that don't have a file name - meaning that no file was selected.
    if (item.getName() == null || item.getName().trim().length() < 1) {
        LOG.debug("No file has been uploaded for the field: " + item.getFieldName());
        return;//from  w  w  w .j  av  a  2s  .  co  m
    }

    List<FileItem> values;
    if (files.get(item.getFieldName()) != null) {
        values = files.get(item.getFieldName());
    } else {
        values = new ArrayList<FileItem>();
    }

    values.add(item);
    files.put(item.getFieldName(), values);
}

From source file:com.ikon.servlet.admin.LanguageServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    boolean persist = WebUtils.getBoolean(request, "persist");
    String userId = request.getRemoteUser();
    Session dbSession = null;/*from w  w w. j  a  v  a 2s.  co  m*/
    updateSessionManager(request);

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Language lang = new Language();
            byte data[] = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("lg_id")) {
                        lang.setId(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("lg_name")) {
                        lang.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("persist")) {
                        persist = true;
                    }
                } else {
                    is = item.getInputStream();
                    data = IOUtils.toByteArray(is);
                    lang.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    is.close();
                }
            }

            if (action.equals("create")) {
                lang.setImageContent(SecureStore.b64Encode(data));
                LanguageDAO.create(lang);

                // Activity log
                UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_CREATE", lang.getId(), null,
                        lang.toString());
            } else if (action.equals("edit")) {
                lang.setImageContent(SecureStore.b64Encode(data));
                LanguageDAO.update(lang);

                // Activity log
                UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_EDIT", lang.getId(), null,
                        lang.toString());
            } else if (action.equals("delete")) {
                LanguageDAO.delete(lang.getId());

                // Activity log
                UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_DELETE", lang.getId(), null, null);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importLanguage(userId, request, response, data, dbSession);

                // Activity log
                UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_IMPORT", null, null, null);
            }
        } else if (action.equals("translate")) {
            translate(userId, request, response);
        } else if (action.equals("addTranslation")) {
            addTranslation(userId, request, response);
        }

        if (!action.equals("addTranslation") && (action.equals("") || action.equals("import") || persist)) {
            list(userId, request, response);
        }
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        HibernateUtil.close(dbSession);
    }
}

From source file:de.ingrid.portal.portlets.ContactPortlet.java

public void processAction(ActionRequest request, ActionResponse actionResponse)
        throws PortletException, IOException {
    List<FileItem> items = null;
    File uploadFile = null;/*from   w  ww .ja  va 2 s.  c  o m*/
    boolean uploadEnable = PortalConfig.getInstance().getBoolean(PortalConfig.PORTAL_CONTACT_UPLOAD_ENABLE,
            Boolean.FALSE);
    int uploadSize = PortalConfig.getInstance().getInt(PortalConfig.PORTAL_CONTACT_UPLOAD_SIZE, 10);

    RequestContext requestContext = (RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV);
    HttpServletRequest servletRequest = requestContext.getRequest();
    if (ServletFileUpload.isMultipartContent(servletRequest)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        factory.setSizeThreshold(uploadSize * 1000 * 1000);
        File file = new File(".");
        factory.setRepository(file);
        ServletFileUpload.isMultipartContent(servletRequest);
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(uploadSize * 1000 * 1000);

        // Parse the request
        try {
            items = upload.parseRequest(servletRequest);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
        }
    }
    if (items != null) {
        // check form input
        if (request.getParameter(PARAMV_ACTION_DB_DO_REFRESH) != null) {

            ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY,
                    ContactForm.class);
            cf.populate(items);

            String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
            actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
            return;
        } else {
            Boolean isResponseCorrect = false;

            ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY,
                    ContactForm.class);
            cf.populate(items);
            if (!cf.validate()) {
                // add URL parameter indicating that portlet action was called
                // before render request

                String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
                actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));

                return;
            }

            //remenber that we need an id to validate!
            String sessionId = request.getPortletSession().getId();
            //retrieve the response
            boolean enableCaptcha = PortalConfig.getInstance().getBoolean("portal.contact.enable.captcha",
                    Boolean.TRUE);

            if (enableCaptcha) {
                String response = request.getParameter("jcaptcha");
                for (FileItem item : items) {
                    if (item.getFieldName() != null) {
                        if (item.getFieldName().equals("jcaptcha")) {
                            response = item.getString();
                            break;
                        }
                    }
                }
                // Call the Service method
                try {
                    isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(sessionId,
                            response);
                } catch (CaptchaServiceException e) {
                    //should not happen, may be thrown if the id is not valid
                }
            }

            if (isResponseCorrect || !enableCaptcha) {
                try {
                    IngridResourceBundle messages = new IngridResourceBundle(
                            getPortletConfig().getResourceBundle(request.getLocale()), request.getLocale());

                    HashMap mailData = new HashMap();
                    mailData.put("user.name.given", cf.getInput(ContactForm.FIELD_FIRSTNAME));
                    mailData.put("user.name.family", cf.getInput(ContactForm.FIELD_LASTNAME));
                    mailData.put("user.employer", cf.getInput(ContactForm.FIELD_COMPANY));
                    mailData.put("user.business-info.telecom.telephone", cf.getInput(ContactForm.FIELD_PHONE));
                    mailData.put("user.business-info.online.email", cf.getInput(ContactForm.FIELD_EMAIL));
                    mailData.put("user.area.of.profession",
                            messages.getString("contact.report.email.area.of.profession."
                                    + cf.getInput(ContactForm.FIELD_ACTIVITY)));
                    mailData.put("user.interest.in.enviroment.info",
                            messages.getString("contact.report.email.interest.in.enviroment.info."
                                    + cf.getInput(ContactForm.FIELD_INTEREST)));
                    if (cf.hasInput(ContactForm.FIELD_NEWSLETTER)) {
                        Session session = HibernateUtil.currentSession();
                        Transaction tx = null;

                        try {

                            mailData.put("user.subscribed.to.newsletter", "yes");
                            // check for email address in newsletter list
                            tx = session.beginTransaction();
                            List newsletterDataList = session.createCriteria(IngridNewsletterData.class)
                                    .add(Restrictions.eq("emailAddress", cf.getInput(ContactForm.FIELD_EMAIL)))
                                    .list();
                            tx.commit();
                            // register for newsletter if not already registered
                            if (newsletterDataList.isEmpty()) {
                                IngridNewsletterData data = new IngridNewsletterData();
                                data.setFirstName(cf.getInput(ContactForm.FIELD_FIRSTNAME));
                                data.setLastName(cf.getInput(ContactForm.FIELD_LASTNAME));
                                data.setEmailAddress(cf.getInput(ContactForm.FIELD_EMAIL));
                                data.setDateCreated(new Date());

                                tx = session.beginTransaction();
                                session.save(data);
                                tx.commit();
                            }
                        } catch (Throwable t) {
                            if (tx != null) {
                                tx.rollback();
                            }
                            throw new PortletException(t.getMessage());
                        } finally {
                            HibernateUtil.closeSession();
                        }
                    } else {
                        mailData.put("user.subscribed.to.newsletter", "no");
                    }
                    mailData.put("message.body", cf.getInput(ContactForm.FIELD_MESSAGE));

                    Locale locale = request.getLocale();

                    String language = locale.getLanguage();
                    String localizedTemplatePath = EMAIL_TEMPLATE;
                    int period = localizedTemplatePath.lastIndexOf(".");
                    if (period > 0) {
                        String fixedTempl = localizedTemplatePath.substring(0, period) + "_" + language + "."
                                + localizedTemplatePath.substring(period + 1);
                        if (new File(getPortletContext().getRealPath(fixedTempl)).exists()) {
                            localizedTemplatePath = fixedTempl;
                        }
                    }

                    String emailSubject = messages.getString("contact.report.email.subject");

                    if (PortalConfig.getInstance().getBoolean("email.contact.subject.add.topic",
                            Boolean.FALSE)) {
                        if (cf.getInput(ContactForm.FIELD_ACTIVITY) != null
                                && !cf.getInput(ContactForm.FIELD_ACTIVITY).equals("none")) {
                            emailSubject = emailSubject + " - "
                                    + messages.getString("contact.report.email.area.of.profession."
                                            + cf.getInput(ContactForm.FIELD_ACTIVITY));
                        }
                    }

                    String from = cf.getInput(ContactForm.FIELD_EMAIL);
                    String to = PortalConfig.getInstance().getString(PortalConfig.EMAIL_CONTACT_FORM_RECEIVER,
                            "foo@bar.com");

                    String text = Utils.mergeTemplate(getPortletConfig(), mailData, "map",
                            localizedTemplatePath);
                    if (uploadEnable) {
                        if (uploadEnable) {
                            for (FileItem item : items) {
                                if (item.getFieldName() != null) {
                                    if (item.getFieldName().equals("upload")) {
                                        uploadFile = new File(sessionId + "_" + item.getName());
                                        // read this file into InputStream
                                        InputStream inputStream = item.getInputStream();

                                        // write the inputStream to a FileOutputStream
                                        OutputStream out = new FileOutputStream(uploadFile);
                                        int read = 0;
                                        byte[] bytes = new byte[1024];

                                        while ((read = inputStream.read(bytes)) != -1) {
                                            out.write(bytes, 0, read);
                                        }

                                        inputStream.close();
                                        out.flush();
                                        out.close();
                                        break;
                                    }
                                }
                            }
                        }
                        Utils.sendEmail(from, emailSubject, new String[] { to }, text, null, uploadFile);
                    } else {
                        Utils.sendEmail(from, emailSubject, new String[] { to }, text, null);
                    }
                } catch (Throwable t) {
                    cf.setError("", "Error sending mail from contact form.");
                    log.error("Error sending mail from contact form.", t);
                }

                // temporarily show same page with content
                String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, PARAMV_ACTION_SUCCESS);
                actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
            } else {
                cf.setErrorCaptcha();
                String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
                actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
                return;
            }
        }
    } else {
        ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY, ContactForm.class);
        cf.setErrorUpload();
        String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
        actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
        return;
    }
}

From source file:it.swim.servlet.profilo.azioni.ModificaProfiloServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*from w ww .  ja va  2  s.  c om*/
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ottengo l'email dell'utente collegato dalla sessione, appoggiandomi
    // ad una classe di utilita'
    String emailUtenteCollegato = (String) UtenteCollegatoUtil.getEmailUtenteCollegato(request);

    // se e' null e' perche' l'utente non e' collegato e allora devo fare il
    // redirect alla home
    if (emailUtenteCollegato == null) {
        response.sendRedirect("../../home");
        return;
    }

    List<FileItem> items;
    Blob blob = null;
    String password = new String();
    String nome = new String();
    String cognome = new String();
    String confermaHiddenInput = new String();

    List<Abilita> abilitaDaAggiungereAllePersonali = new ArrayList<Abilita>();

    try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input
                // type="text|radio|checkbox|etc", select, etc).
                // ... (do your job here)
                if (item.getFieldName().equals("password")) {
                    password = item.getString();
                }
                if (item.getFieldName().equals("nome")) {
                    nome = item.getString();
                }
                if (item.getFieldName().equals("cognome")) {
                    cognome = item.getString();
                }
                if (item.getFieldName().equals("abilita")) {
                    abilitaDaAggiungereAllePersonali.add(registrazione.getAbilitaByNome(item.getString()));
                }
                if (item.getFieldName().equals("conferma")) {
                    confermaHiddenInput = item.getString();
                }
            } else {
                //non cancellare questi commenti, potranno tornare utili
                // Process form file field (input type="file").
                // String fieldname = item.getFieldName();
                // String filename = item.getName();
                // InputStream filecontent = item.getInputStream();
                try {
                    blob = ConvertitoreFotoInBlob.getBlobFromFileItem(item, LUNGHEZZA, ALTEZZA, DIMMB);
                } catch (FotoException e) {
                    if (e.getCausa().equals(FotoException.Causa.FILETROPPOGRANDE)) {
                        request.setAttribute("erroreFileTroppoGrande",
                                "Errore, file troppo grande! La foto attuale del profilo non e' stata modificata");
                    } else {
                        if (e.getCausa().equals(FotoException.Causa.NONRICONOSCIUTACOMEFOTO)) {
                            request.setAttribute("erroreNonFoto",
                                    "Errore, foto non riconosciuta! La foto attuale del profilo non e' stata modificata");
                        }
                    }
                    //in questo caso uploada una foto predefinita
                    request.setAttribute("erroreFotoSconosciuto",
                            "Errore durante il caricamento della foto! La foto attuale del profilo non e' stata modificata");
                }
            }
        }

        log.debug("password: " + password);
        log.debug("nome: " + nome);
        log.debug("cognome: " + cognome);
        log.debug("Lista abilita da aggiungere all'utente: "
                + Arrays.toString(abilitaDaAggiungereAllePersonali.toArray()));
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        request.setAttribute("erroreInserimentoFoto", "Errore nel caricamento della nuova foto del profilo");
    } catch (SerialException e) {
        log.error(e.getMessage(), e);
        request.setAttribute("erroreInserimentoFoto", "Errore nel caricamento della nuova foto del profilo");
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        request.setAttribute("erroreInserimentoFoto", "Errore nel caricamento della nuova foto del profilo");
    }

    log.debug("abilitaDaAggiungereAllePersonali : "
            + Arrays.toString(abilitaDaAggiungereAllePersonali.toArray()));

    if (confermaHiddenInput != null && confermaHiddenInput.equals("CONFERMA")) {

        if (abilitaDaAggiungereAllePersonali.size() >= 1) {
            boolean modificaInsiemePersonaleAbilita = modificaProfilo
                    .modificaInsiemePersonaleAbilita(emailUtenteCollegato, abilitaDaAggiungereAllePersonali);
            log.debug("modificaInsiemePersonaleAbilita: " + modificaInsiemePersonaleAbilita);
            if (modificaInsiemePersonaleAbilita) {
                request.setAttribute("modificaAbilitaRiuscitaConSuccesso", "Modifica eseguita correttamente");
            } else {
                log.debug("Errore inserimento abilita");
                request.setAttribute("erroreInserimentoProposta", "Errore nell'aggiunta di nuove abilita'");
            }
        }

        if (blob != null) {
            boolean modificaFotoRiuscita = modificaProfilo.modificaFoto(emailUtenteCollegato, blob);
            log.debug("modificaFotoRiuscita: " + modificaFotoRiuscita);
            if (modificaFotoRiuscita) {
                request.setAttribute("modificaFotoRiuscitaConSuccesso", "Modifica eseguita correttamente");
            } else {
                log.debug("Errore modifica foto");
                request.setAttribute("erroreInserimentoFoto",
                        "Errore nel caricamento della nuova foto del profilo");
            }
        }

    } else {
        request.setAttribute("nonHaiConfermatoInvioForm",
                "Hai interrotto la procedura. Nessun dato e' stato inviato");
    }

    try {
        request.setAttribute("abilita", this.getListaAbilitaAggiungibili(emailUtenteCollegato));
    } catch (RicercheException e) {
        log.error(e.getMessage(), e);
        request.setAttribute("erroreGelListaAbilitaAggiungibili",
                "Errore caricamento abilita' modificabili dall'utente");
    }

    getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/modificaProfilo.jsp")
            .forward(request, response);
}