Example usage for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest.

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:com.safetys.framework.fckeditor.connector.Dispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * /*  w w  w  . j a  v a 2  s. c  o  m*/
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
@SuppressWarnings("unchecked")
UploadResponse doPost(final HttpServletRequest request) {
    Dispatcher.logger.debug("Entering Dispatcher#doPost");

    final Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request)) {
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    } else if (!Command.isValidForPost(context.getCommandStr())) {
        uploadResponse = UploadResponse.getInvalidCommandError();
    } else if (!ResourceType.isValidType(context.getTypeStr())) {
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    } else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) {
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    } else {

        // call the Connector#fileUpload
        final ResourceType type = context.getDefaultResourceType();
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            final List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            final FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            final String fileName = FilenameUtils.getName(uplFile.getName());
            Dispatcher.logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                final String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                Dispatcher.logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                final String newFileName = this.connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                final String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request),
                        type, context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName)) {
                    uploadResponse = UploadResponse.getOK(fileUrl);
                } else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    Dispatcher.logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            uplFile.delete();
        } catch (final InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (final WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (final IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (final FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    Dispatcher.logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}

From source file:br.com.caelum.vraptor.observer.upload.CommonsUploadMultipartObserver.java

public void upload(@Observes ControllerFound event, MutableRequest request, MultipartConfig config,
        Validator validator) {//from   www . j  a va 2  s  . c  o  m

    if (!ServletFileUpload.isMultipartContent(request)) {
        return;
    }

    logger.info("Request contains multipart data. Try to parse with commons-upload.");

    final Multiset<String> indexes = HashMultiset.create();
    final Multimap<String, String> params = LinkedListMultimap.create();

    ServletFileUpload uploader = createServletFileUpload(config);
    uploader.setSizeMax(config.getSizeLimit());
    uploader.setFileSizeMax(config.getFileSizeLimit());

    try {
        final List<FileItem> items = uploader.parseRequest(request);
        logger.debug("Found {} attributes in the multipart form submission. Parsing them.", items.size());

        for (FileItem item : items) {
            String name = item.getFieldName();
            name = fixIndexedParameters(name, indexes);

            if (item.isFormField()) {
                logger.debug("{} is a field", name);
                params.put(name, getValue(item, request));

            } else if (isNotEmpty(item)) {
                logger.debug("{} is a file", name);
                processFile(item, name, request);

            } else {
                logger.debug("A file field is empty: {}", item.getFieldName());
            }
        }

        for (String paramName : params.keySet()) {
            Collection<String> paramValues = params.get(paramName);
            request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()]));
        }

    } catch (final SizeLimitExceededException e) {
        reportSizeLimitExceeded(e, validator);

    } catch (FileUploadException e) {
        reportFileUploadException(e, validator);
    }
}

From source file:edu.lternet.pasta.portal.UploadEvaluateServlet.java

/**
 * The doPost method of the servlet. <br>
 * //from   w w  w  . ja va2 s.c  o m
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession httpSession = request.getSession();

    String uid = (String) httpSession.getAttribute("uid");

    if (uid == null || uid.isEmpty())
        uid = "public";

    String html = null;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

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

        // Parse the request
        try {

            List /* FileItem */ items = upload.parseRequest(request);

            // Process the uploaded items
            Iterator iter = items.iterator();

            while (iter.hasNext()) {

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

                if (!(item.isFormField())) {

                    File eml = processUploadedFile(item);

                    DataPackageManagerClient dpmClient = new DataPackageManagerClient(uid);
                    String xml = dpmClient.evaluateDataPackage(eml);

                    ReportUtility qrUtility = new ReportUtility(xml);
                    String htmlTable = qrUtility.xmlToHtmlTable(cwd + xslpath);

                    if (htmlTable == null) {
                        String msg = "The uploaded file could not be evaluated.";
                        throw new UserErrorException(msg);
                    } else {
                        html = HTMLHEAD + "<div class=\"qualityreport\">" + htmlTable + "</div>" + HTMLTAIL;
                    }

                }

            }

        } catch (Exception e) {
            handleDataPortalError(logger, e);
        }
    }

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.print(html);
    out.flush();
    out.close();
}

From source file:com.nominanuda.web.http.ServletHelper.java

@SuppressWarnings("unchecked")
private HttpEntity buildEntity(HttpServletRequest servletRequest, final InputStream is, long contentLength,
        String ct, String cenc) throws IOException {
    if (ServletFileUpload.isMultipartContent(servletRequest)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items;
        try {/*from www. j  a v  a  2s  .  c om*/
            items = upload.parseRequest(new HttpServletRequestWrapper(servletRequest) {
                public ServletInputStream getInputStream() throws IOException {
                    return new ServletInputStream() {
                        public int read() throws IOException {
                            return is.read();
                        }

                        public int read(byte[] arg0) throws IOException {
                            return is.read(arg0);
                        }

                        public int read(byte[] b, int off, int len) throws IOException {
                            return is.read(b, off, len);
                        }

                        //@Override
                        @SuppressWarnings("unused")
                        public boolean isFinished() {
                            Check.illegalstate.fail(NOT_IMPLEMENTED);
                            return false;
                        }

                        //@Override
                        @SuppressWarnings("unused")
                        public boolean isReady() {
                            Check.illegalstate.fail(NOT_IMPLEMENTED);
                            return false;
                        }

                        //@Override
                        @SuppressWarnings("unused")
                        public void setReadListener(ReadListener arg0) {
                            Check.illegalstate.fail(NOT_IMPLEMENTED);
                        }
                    };
                }
            });
        } catch (FileUploadException e) {
            throw new IOException(e);
        }
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (FileItem i : items) {
            multipartEntity.addPart(i.getFieldName(), new InputStreamBody(i.getInputStream(), i.getName()));
        }
        return multipartEntity;
    } else {
        InputStreamEntity entity = new InputStreamEntity(is, contentLength);
        entity.setContentType(ct);
        if (cenc != null) {
            entity.setContentEncoding(cenc);
        }
        return entity;
    }
}

From source file:edu.gmu.csiss.automation.pacs.servlet.FileUploadServlet.java

/**
 * Processes requests for both HTTP/*  www .j a  va 2  s  .  co  m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @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 req, HttpServletResponse res)
        throws ServletException, IOException {
    res.setContentType("text/plain;charset=gbk");

    res.setContentType("text/html; charset=utf-8");
    PrintWriter pw = res.getWriter();
    try {
        //initialize the prefix url
        if (prefix_url == null) {
            //                String hostname = req.getServerName ();
            //                int port = req.getServerPort ();
            //                prefix_url = "http://"+hostname+":"+port+"/igfds/"+relativePath+"/";
            //updated by Ziheng - on 8/27/2015
            //This method should be used everywhere.
            int num = req.getRequestURI().indexOf("/PACS");
            String prefix = req.getRequestURI().substring(0, num + "/PACS".length()); //in case there is something before PACS
            prefix_url = req.getScheme() + "://" + req.getServerName()
                    + ("http".equals(req.getScheme()) && req.getServerPort() == 80
                            || "https".equals(req.getScheme()) && req.getServerPort() == 443 ? ""
                                    : ":" + req.getServerPort())
                    + prefix + "/" + relativePath + "/";
        }
        pw.println("<!DOCTYPE html>");
        pw.println("<html>");
        String head = "<head>" + "<title>File Uploading Response</title>"
                + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
                + "<script type=\"text/javascript\" src=\"js/TaskGridTool.js\"></script>" + "</head>";
        pw.println(head);
        pw.println("<body>");

        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        // threshold  2M 
        //extend to 2M - updated by ziheng - 9/25/2014
        diskFactory.setSizeThreshold(2 * 1024);
        // repository 
        diskFactory.setRepository(new File(tempPath));

        ServletFileUpload upload = new ServletFileUpload(diskFactory);
        // 2M
        upload.setSizeMax(2 * 1024 * 1024);
        // HTTP
        List fileItems = upload.parseRequest(req);
        Iterator iter = fileItems.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                processFormField(item, pw);
            } else {
                processUploadFile(item, pw);
            }
        } // end while()
          //add some buttons for further process
        pw.println("<input type=\"button\" id=\"bt\" value=\"load\" onclick=\"load();\">");
        pw.println("<input type=\"button\" id=\"close\" value=\"close window\" onclick=\"window.close();\">");
        pw.println("</body>");
        pw.println("</html>");
    } catch (Exception e) {
        e.printStackTrace();
        pw.println("ERR:" + e.getClass().getName() + ":" + e.getLocalizedMessage());
    } finally {
        pw.flush();
        pw.close();
    }
}

From source file:it.geosolutions.geofence.gui.server.UploadServlet.java

@SuppressWarnings("unchecked")
@Override/*w w  w  .  j a  v  a  2 s  .c o  m*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

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

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

        File uploadedFile = null;
        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(req);

            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    continue;
                }

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                uploadedFile = File.createTempFile(fileName, "");
                // if (uploadedFile.createNewFile()) {
                item.write(uploadedFile);
                resp.setStatus(HttpServletResponse.SC_CREATED);
                resp.flushBuffer();

                // uploadedFile.delete();
                // } else
                // throw new IOException(
                // "The file already exists in repository.");
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

        try {
            String wkt = calculateWKT(uploadedFile);
            resp.getWriter().print(wkt);
        } catch (Exception exc) {
            resp.getWriter().print("Error : " + exc.getMessage());
            logger.error("ERROR ********** " + exc);
        }

        uploadedFile.delete();

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:com.intranet.intr.proyecto.EmpControllerProyectoGaleriaCertificaciones.java

@RequestMapping(value = "EProyectoGaleria.htm", method = RequestMethod.POST)
public String ProyectoGaleria_post(@ModelAttribute("fotogaleria") proyecto_certificaciones_galeria galer,
        BindingResult result, HttpServletRequest request) {
    String mensaje = "";
    //C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosCertificaciones";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);//from  w  ww  .j ava 2  s .  co  m

    ServletFileUpload upload = new ServletFileUpload(factory);
    String ruta = "redirect:EProyectoGaleria.htm?nifC=" + nifC + "&id=" + idP;
    try {
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            if (idP != 0) {
                galer.setIdPropuesta(idP);
                if (proyectoCertificacionesGaleriaService.existe(item.getName()) == false) {

                    File file = new File(ubicacionArchivo, item.getName());
                    item.write(file);
                    galer.setNombreimg(item.getName());
                    proyectoCertificacionesGaleriaService.insertar2(galer);
                }
            } else
                ruta = "redirect:ELtaClientesProyecto.htm";
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    //return "redirect:uploadFile.htm";

    return ruta;

}

From source file:calliope.handler.put.AesePutHandler.java

private void parseRequest(HttpServletRequest request) throws AeseException {
    try {/*ww w.j av a 2s.  c o  m*/
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString();
                    if (fieldName.equals(Params.STRIPPER))
                        stripperName = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.STYLE))
                        style = contents;
                    else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.VERSION1))
                        version1 = contents;
                    else if (fieldName.equals(Params.AUTHOR))
                        author = contents;
                    else if (fieldName.equals(Params.DESCRIPTION))
                        description = contents;
                }
            } else if (item.getName().length() > 0) {
                byte[] rawData = item.get();
                guessEncoding(rawData);
                if (encoding == null)
                    encoding = guessEncoding(rawData);
                fileContent = new String(rawData, encoding);
            }
        }
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:com.intranet.intr.proyecto.SupControllerProyectoGaleriaCertificaciones.java

@RequestMapping(value = "ProyectoGaleria.htm", method = RequestMethod.POST)
public String ProyectoGaleria_post(@ModelAttribute("fotogaleria") proyecto_certificaciones_galeria galer,
        BindingResult result, HttpServletRequest request) {
    String mensaje = "";
    //C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\
    String ubicacionArchivo = "E:\\";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);/* www  . j  av a2s .co  m*/

    ServletFileUpload upload = new ServletFileUpload(factory);
    String ruta = "redirect:ProyectoGaleria.htm?nifC=" + nifC + "&id=" + idP;
    try {
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            if (idP != 0) {
                galer.setIdPropuesta(idP);
                if (proyectoCertificacionesGaleriaService.existe(item.getName()) == false) {

                    File file = new File(ubicacionArchivo, item.getName());
                    item.write(file);
                    galer.setNombreimg(item.getName());
                    proyectoCertificacionesGaleriaService.insertar2(galer);
                }
            } else
                ruta = "redirect:SLtaClientesProyecto.htm";
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    //return "redirect:uploadFile.htm";

    return ruta;

}

From source file:com.antinymail.ventadecasas.servlet.UploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;//from   w w w .j a v a2 s.  co m
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    //factory.setRepository(new File("c:\\temp"));

    //factory.setRepository(new File("C:\\Users\\Susana\\Documents\\NetBeansProjects\\VentadeCasas\\web\\images")); 

    factory.setRepository(
            new File("C:\\Users\\Susana\\Documents\\NetBeansProjects\\VentadeCasas\\web\\images"));

    //factory.setRepository(new File("//petylde.esy.es//uploads//casapueblo"));
    //factory.setRepository(new Uri());

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

    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {

                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));

                    //file = new File( fileName);

                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));

                    //file = new File( fileName);
                }
                fi.write(file);
                //fi.write( fileNa ) ;  

                out.println("Uploaded Filename: " + fileName + "<br>");
                out.println("La ruta inicial era: " + filePath + "<br>");

            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}