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

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

Introduction

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

Prototype

public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException 

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:pl.exsio.plupload.PluploadReceiver.java

@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response)
        throws IOException {
    if (request.getPathInfo() != null && request.getPathInfo().endsWith(UPLOAD_ACTION_PATH)) {
        if (request instanceof VaadinServletRequest) {
            VaadinServletRequest vsr = (VaadinServletRequest) request;
            HttpServletRequest req = vsr.getHttpServletRequest();
            if (ServletFileUpload.isMultipartContent(req)) {
                try {
                    synchronized (this) {
                        ServletFileUpload upload = new ServletFileUpload();
                        FileItemIterator items = upload.getItemIterator(req);
                        PluploadChunk chunk = PluploadChunkFactory.create(items);
                        PluploadChunkHandler fileHandler = this.getExpectedFileHandler(chunk.getFileId());
                        fileHandler.handleUploadedChunk(chunk);
                        this.writeResponse(chunk, response);
                    }/*from   w w  w .j  av  a2  s. c o  m*/
                } catch (Exception ex) {
                    response.getWriter().append("file upload unsuccessful, because of "
                            + ex.getClass().getName() + ":" + ex.getMessage());
                    throw new IOException(
                            "There was a problem during processing of uploaded chunk. Nested exceptions may have more info.",
                            ex);
                }
                return true;
            }
        }
    }
    return false;

}

From source file:Project.FileUploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from www . j  av  a2s .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 {
    //processRequest(request, response);
    response.setContentType("text/html");
    String path = "";
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {
            String category = "";
            String keywords = "";
            double cost = 0.0;
            String imagess = "";
            String user = "";
            FileItemIterator itr = upload.getItemIterator(request);
            Map<String, String> map = new HashMap<String, String>();
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    //do variable declaration of the specific field
                    String fieldName = item.getFieldName();
                    InputStream is = item.openStream();
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    response.getWriter().println(fieldName + ":" + value + "<br/>");
                    map.put(fieldName, value);
                } else {
                    //do file upload and store the path as variable
                    path = getServletContext().getRealPath("/");
                    //will write a method and we will call here
                    if (processFile(path, item)) {
                        response.getWriter().println("File uploaded successfully");
                        response.getWriter().println(path);
                    } else {
                        response.getWriter().println("File uploading failed");
                    }
                }

                for (Map.Entry<String, String> entry : map.entrySet()) {
                    if (entry.getKey().equals("category")) {
                        category = entry.getValue();
                    } else if (entry.getKey().equals("keywords")) {
                        keywords = entry.getValue();
                    } else if (entry.getKey().equals("cost")) {
                        cost = Double.parseDouble(entry.getValue());
                    } else if (entry.getKey().equals("fileName")) {
                        imagess = entry.getValue();
                    } else if (entry.getKey().equals("user")) {
                        user = entry.getValue();
                    }
                }

            }
            response.getWriter().println("images\\" + imagess);
            imagess = "images\\" + imagess;
            response.getWriter().println(category + "---" + keywords + "----" + cost + "---" + imagess);
            DB_Users d = new DB_Users();
            d.insertProduct(category, keywords, imagess, cost, user);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    } else {
        //do nothing
    }
}

From source file:ru.arch_timeline.spring.multipart.StreamingMultipartResolver.java

public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);

    String encoding = determineEncoding(request);

    //Map<String, MultipartFile> multipartFiles = new HashMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartContentTypes = new HashMap<String, String>();

    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();

    // Parse the request
    try {/*from  w w w  .  ja va2s .  c  o m*/
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {

                String value = Streams.asString(stream, encoding);

                String[] curParam = (String[]) multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }

            } else {

                // Process the input stream
                MultipartFile file = new StreamingMultipartFile(item);
                multipartFiles.add(name, file);
                multipartContentTypes.put(name, file.getContentType());
            }
        }
    } catch (IOException e) {
        throw new MultipartException("something went wrong here", e);
    } catch (FileUploadException e) {
        throw new MultipartException("something went wrong here", e);
    }

    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters,
            multipartContentTypes);
}

From source file:rurales.FileUploadRural.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  ww  w .j  a  v  a2s  . 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 {
    ConectionDB con = new ConectionDB();
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String Unidad = "";

    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {
            HttpSession sesion = request.getSession(true);
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    String fielName = item.getFieldName();
                    InputStream is = item.openStream();
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    response.getWriter().println(fielName + ":" + value + "<br/>");
                } else {
                    String path = getServletContext().getRealPath("/");
                    if (FileUpload.processFile(path, item)) {
                        //response.getWriter().println("file uploaded successfully");
                        if (lee.obtieneArchivo(path, item.getName())) {
                            out.println("<script>alert('Se carg el Folio Correctamente')</script>");
                            out.println("<script>window.location='requerimiento.jsp'</script>");
                        }
                        //response.sendRedirect("cargaFotosCensos.jsp");
                    } else {
                        //response.getWriter().println("file uploading falied");
                        //response.sendRedirect("cargaFotosCensos.jsp");
                    }
                }
            }
        } catch (FileUploadException fue) {
            fue.printStackTrace();
        }
        out.println("<script>alert('No se pudo cargar el Folio, verifique las celdas')</script>");
        out.println("<script>window.location='requerimiento.jsp'</script>");
        //response.sendRedirect("carga.jsp");
    }

    /*
     * Para insertar el excel en tablas
     */
}

From source file:simulator.scl.factory.UploadedConfigurationFactory.java

public Configuration createConfiguration() throws IOException {
    try {//from  w w w .ja  va  2s  .com
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);

        final InputStream stream = upload.getItemIterator(request).next().openStream();

        final Resource resource = EmfUtil.createResource(ConfigPackage.eINSTANCE);
        resource.load(stream, Collections.emptyMap());

        return (Configuration) resource.getContents().get(0);

    } catch (FileUploadException e) {
        throw new IOException("Error encountered whilst uploading file", e);
    }
}

From source file:tech.oleks.pmtalk.PmTalkServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Order o = new Order();
    ServletFileUpload upload = new ServletFileUpload();
    try {// w ww  . j  av  a2  s .co m
        FileItemIterator it = upload.getItemIterator(req);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            InputStream fieldValue = item.openStream();
            String fieldName = item.getFieldName();
            if ("candidate".equals(fieldName)) {
                String candidate = Streams.asString(fieldValue);
                o.setCandidate(candidate);
            } else if ("staffing".equals(fieldName)) {
                String staffingLink = Streams.asString(fieldValue);
                o.setStaffingLink(staffingLink);
            } else if ("resume".equals(fieldName)) {
                FileUpload resume = new FileUpload();
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(fieldValue, os);
                resume.setStream(new ByteArrayInputStream(os.toByteArray()));
                resume.setContentType(item.getContentType());
                resume.setFileName(item.getName());
                o.setResume(resume);
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    pmTalkService.minimal(o);
    req.setAttribute("order", o);
    if (o.getErrors() != null) {
        forward("/form.jsp", req, resp);
    } else {
        forward("/created.jsp", req, resp);
    }
}

From source file:temporal.web.DemoServlet.java

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

    InputStream in = null;// w w  w. j a  v  a2 s  . c o  m
    OutputStream out = null;

    try {
        response.setContentType(mDemo.responseType());
        out = response.getOutputStream();

        @SuppressWarnings("unchecked") // bad inherited API from commons
        Properties properties = mapToProperties((Map<String, String[]>) request.getParameterMap());

        String reqContentType = request.getContentType();

        if (reqContentType == null || reqContentType.startsWith("text/plain")) {
            properties.setProperty("inputType", "text/plain");
            String reqCharset = request.getCharacterEncoding();
            if (reqCharset != null)
                properties.setProperty("inputCharset", reqCharset);
            in = request.getInputStream();

        } else if (reqContentType.startsWith("application/x-www-form-urlencoded")) {
            String codedText = request.getParameter("inputText");
            byte[] bytes = codedText.getBytes("ISO-8859-1");
            in = new ByteArrayInputStream(bytes);

        } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload uploader = new ServletFileUpload(factory);
            FileItemIterator it = uploader.getItemIterator(request);
            /*  @SuppressWarnings("unchecked") // bad commons API
            /*  List<FileItem> items = (List<FileItem>) uploader.parseRequest(request);
              Iterator<FileItem> it = items.iterator();*/
            while (it.hasNext()) {
                log("found item");
                FileItemStream item = it.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    String key = item.getFieldName();
                    //   String val = item.getString();
                    String val = org.apache.commons.fileupload.util.Streams.asString(stream);
                    properties.setProperty(key, val);
                } else {
                    byte[] bytes = org.apache.commons.fileupload.util.Streams.asString(stream).getBytes();
                    in = new ByteArrayInputStream(bytes);
                }
            }

        } else {
            System.out.println("unexpected content type");
            String msg = "Unexpected request content" + reqContentType;
            throw new ServletException(msg);
        }
        mDemo.process(in, out, properties);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    } finally {
        Streams.closeQuietly(in);
        Streams.closeQuietly(out);
    }
}

From source file:uk.ac.ebi.sail.server.service.UploadSvc.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

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

    String res = null;//from  ww  w .  j  a  va2 s .  co m
    int studyID = -1;
    int collectionID = -1;

    String fileContent = null;

    String upType = null;

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                if ("CollectionID".equals(name)) {
                    try {
                        collectionID = Integer.parseInt(Streams.asString(stream));
                    } catch (Exception e) {
                    }
                }
                if ("StudyID".equals(name)) {
                    try {
                        studyID = Integer.parseInt(Streams.asString(stream));
                    } catch (Exception e) {
                    }
                } else if ("UploadType".equals(name)) {
                    upType = Streams.asString(stream);
                }

                //     System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
            } else {
                //     System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
                InputStream uploadedStream = item.openStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                StreamPump.doPump(uploadedStream, baos);

                byte[] barr = baos.toByteArray();

                if ((barr[0] == -1 && barr[1] == -2) || (barr[0] == -2 && barr[1] == -1))
                    fileContent = new String(barr, "UTF-16");
                else
                    fileContent = new String(barr);
            }
        }
    } catch (Exception ex) {
        res = ex.getMessage();
        ex.printStackTrace();
    }

    if (fileContent != null) {
        if ("AvailabilityData".equals(upType)) {
            if (collectionID != -1) {
                try {
                    DataManager.getInstance().importData(fileContent, collectionID);
                } catch (Exception ex) {
                    res = ex.getMessage();
                    ex.printStackTrace();
                }
            } else
                res = "Invalid or absent collection ID";
        } else if ("RelationMap".equals(upType)) {
            try {
                DataManager.getInstance().importRelations(new String(fileContent));
            } catch (Exception ex) {
                res = ex.getMessage();
                ex.printStackTrace();
            }
        } else if ("Study2SampleRelation".equals(upType)) {
            try {
                DataManager.getInstance().importSample2StudyRelations(new String(fileContent), studyID,
                        collectionID);
            } catch (Exception ex) {
                res = ex.getMessage();
                ex.printStackTrace();
            }
        } else {
            try {
                DataManager.getInstance().importParameters(fileContent);
            } catch (ParseException pex) {
                res = "Line " + pex.getLineNumber() + ": " + pex.getMessage();
            } catch (Exception ex) {
                res = ex.getMessage();
                ex.printStackTrace();
            }

        }

    } else {
        res = "File content not found";
    }

    JSONObject response = null;
    try {
        response = new JSONObject();
        response.put("success", res == null);
        response.put("error", res == null ? "uploaded successfully" : res);
        response.put("code", "232");
    } catch (Exception e) {

    }

    Writer w = new OutputStreamWriter(resp.getOutputStream());
    w.write(response.toString());
    System.out.println(response.toString());
    w.close();
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:us.mn.state.health.lims.analyzerimport.action.AnalyzerImportServlet.java

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

    String password = null;//w w  w .j ava  2s .co  m
    String user = null;
    AnalyzerReader reader = null;
    boolean fileRead = false;

    InputStream stream = null;

    try {
        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            stream = item.openStream();

            String name = null;

            if (item.isFormField()) {

                if (PASSWORD.equals(item.getFieldName())) {
                    password = streamToString(stream);
                } else if (USER.equals(item.getFieldName())) {
                    user = streamToString(stream);
                }

            } else {

                name = item.getName();

                reader = AnalyzerReaderFactory.getReaderFor(name);

                if (reader != null) {
                    fileRead = reader.readStream(new InputStreamReader(stream));
                }
            }

            stream.close();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                //   LOG.warning(e.toString());
            }
        }
    }

    if (GenericValidator.isBlankOrNull(user) || GenericValidator.isBlankOrNull(password)) {
        response.getWriter().print("missing user");
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        return;
    }

    if (!userValid(user, password)) {
        response.getWriter().print("invalid user/password");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (fileRead) {
        boolean successful = reader.insertAnalyzerData(systemUserId);

        if (successful) {
            response.getWriter().print("success");
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } else {
            response.getWriter().print(reader.getError());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

    } else {
        response.getWriter().print(reader.getError());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

}

From source file:zutil.jee.upload.AjaxFileUpload.java

@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    FileUploadListener listener = new FileUploadListener();
    try {//from  w  w w  .  j ava2  s. c o  m
        // Initiate list and HashMap that will contain the data
        HashMap<String, String> fields = new HashMap<String, String>();
        ArrayList<FileItem> files = new ArrayList<FileItem>();

        // Add the listener to the session
        HttpSession session = request.getSession();
        LinkedList<FileUploadListener> list = (LinkedList<FileUploadListener>) session
                .getAttribute(SESSION_FILEUPLOAD_LISTENER);
        if (list == null) {
            list = new LinkedList<FileUploadListener>();
            session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list);
        }
        list.add(listener);

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        if (TEMPFILE_PATH != null)
            factory.setRepository(TEMPFILE_PATH);
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setProgressListener(listener);
        // Set overall request size constraint
        //upload.setSizeMax(yourMaxRequestSize);

        // Parse the request
        FileItemIterator it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            // Is the file type allowed?
            if (!item.isFormField()
                    && !ALLOWED_EXTENSIONS.contains(FileUtil.getFileExtension(item.getName()).toLowerCase())) {
                String msg = "Filetype '" + FileUtil.getFileExtension(item.getName()) + "' is not allowed!";
                logger.warning(msg);
                listener.setStatus(Status.Error);
                listener.setFileName(item.getName());
                listener.setMessage(msg);
                return;
            }
            listener.setFileName(item.getName());
            FileItem fileItem = factory.createItem(item.getFieldName(), item.getContentType(),
                    item.isFormField(), item.getName());
            // Read the file data
            Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
            if (fileItem instanceof FileItemHeadersSupport) {
                final FileItemHeaders fih = item.getHeaders();
                ((FileItemHeadersSupport) fileItem).setHeaders(fih);
            }

            //Handle the item
            if (fileItem.isFormField()) {
                fields.put(fileItem.getFieldName(), fileItem.getString());
            } else {
                files.add(fileItem);
                logger.info("Recieved file: " + fileItem.getName() + " ("
                        + StringUtil.formatByteSizeToString(fileItem.getSize()) + ")");
            }
        }
        // Process the upload
        listener.setStatus(Status.Processing);
        doUpload(request, response, fields, files);
        // Done
        listener.setStatus(Status.Done);
    } catch (Exception e) {
        logger.log(Level.SEVERE, null, e);
        listener.setStatus(Status.Error);
        listener.setFileName("");
        listener.setMessage(e.getMessage());
    }
}