Example usage for org.apache.commons.fileupload FileItemIterator hasNext

List of usage examples for org.apache.commons.fileupload FileItemIterator hasNext

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemIterator hasNext.

Prototype

boolean hasNext() throws FileUploadException, IOException;

Source Link

Document

Returns, whether another instance of FileItemStream is available.

Usage

From source file:org.waterforpeople.mapping.app.web.PhotoUpload.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    Properties props = System.getProperties();

    String bucket = props.getProperty("s3bucket");
    ServletFileUpload upload = new ServletFileUpload();
    try {//  w w w  .  j av a  2 s. c  o  m
        FileItemIterator iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream in = item.openStream();
            ByteArrayOutputStream out = null;
            try {

                in = item.openStream();
                out = new ByteArrayOutputStream();
                byte[] buffer = new byte[8096];
                int size;

                while ((size = in.read(buffer, 0, buffer.length)) != -1) {
                    out.write(buffer, 0, size);
                }
            } catch (IOException e) {
                log.log(Level.SEVERE, "Could not rotate image", e);
            }
            S3Driver s3 = new S3Driver();
            s3.uploadFile(bucket, "images/" + item.getName(), out.toByteArray());
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Could not save image", e);
    }

}

From source file:password.pwm.http.PwmRequest.java

public Map<String, FileUploadItem> readFileUploads(final int maxFileSize, final int maxItems)
        throws IOException, ServletException, PwmUnrecoverableException {
    final Map<String, FileUploadItem> returnObj = new LinkedHashMap<>();
    try {/*from   w ww  . j a  v a 2 s  .co  m*/
        if (ServletFileUpload.isMultipartContent(this.getHttpServletRequest())) {
            final ServletFileUpload upload = new ServletFileUpload();
            final FileItemIterator iter = upload.getItemIterator(this.getHttpServletRequest());
            while (iter.hasNext() && returnObj.size() < maxItems) {
                final FileItemStream item = iter.next();
                final InputStream inputStream = item.openStream();
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                final long length = IOUtils.copyLarge(inputStream, baos, 0, maxFileSize + 1);
                if (length > maxFileSize) {
                    final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN,
                            "upload file size limit exceeded");
                    LOGGER.error(this, errorInformation);
                    respondWithError(errorInformation);
                    return Collections.emptyMap();
                }
                final byte[] outputFile = baos.toByteArray();
                final FileUploadItem fileUploadItem = new FileUploadItem(item.getName(), item.getContentType(),
                        outputFile);
                returnObj.put(item.getFieldName(), fileUploadItem);
            }
        }
    } catch (Exception e) {
        LOGGER.error("error reading file upload: " + e.getMessage());
    }
    return Collections.unmodifiableMap(returnObj);
}

From source file:pl.exsio.plupload.PluploadChunkFactory.java

public static PluploadChunk create(FileItemIterator items) throws IOException, FileUploadException {
    PluploadChunk chunk = new PluploadChunk();
    while (items.hasNext()) {
        FileItemStream item = (FileItemStream) items.next();

        if (item.isFormField()) {
            setChunkField(chunk, item);//from w w  w  .  ja  va  2  s . co  m
        } else {
            saveChunkData(chunk, item);
            break;
        }
    }
    return chunk;
}

From source file:Project.FileUploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w  ww  . ja  v  a  2 s .  c  o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //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   ww w .ja  v a 2s .  c om
        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/*from   www. j a va  2s  .  c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    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:se.vgregion.portal.innovationsslussen.idea.controller.IdeaViewController.java

/**
 * Upload file action./*w w w.j av a 2  s  .c  o  m*/
 *
 * @param request  the request
 * @param response the response
 * @param model    the model
 * @throws FileUploadException the file upload exception
 */
@ActionMapping(params = "action=uploadFile")
public void uploadFile(ActionRequest request, ActionResponse response, Model model)
        throws FileUploadException, SystemException, PortalException {

    ThemeDisplay themeDisplay = getThemeDisplay(request);
    long scopeGroupId = themeDisplay.getScopeGroupId();
    long userId = themeDisplay.getUserId();

    String urlTitle = request.getParameter("urlTitle");

    String fileType = request.getParameter("fileType");
    boolean publicIdea;
    if (fileType.equals("public")) {
        publicIdea = true;
    } else if (fileType.equals("private")) {
        publicIdea = false;
    } else {
        throw new IllegalArgumentException("Unknown filetype: " + fileType);
    }

    //TODO ondig slagning? Cacha?
    Idea idea = ideaService.findIdeaByUrlTitle(urlTitle);
    //TODO Kan det inte finnas flera med samma titel i olika communities?

    IdeaContentType ideaContentType = publicIdea ? IdeaContentType.IDEA_CONTENT_TYPE_PUBLIC
            : IdeaContentType.IDEA_CONTENT_TYPE_PRIVATE;

    if (!isAllowedToDoAction(request, idea, Action.UPLOAD_FILE, ideaContentType)) {
        sendRedirectToContextRoot(response);
        return;
    }

    boolean mayUploadFile = idea.getUserId() == userId;

    IdeaPermissionChecker ideaPermissionChecker = ideaPermissionCheckerService
            .getIdeaPermissionChecker(scopeGroupId, userId, idea);

    if (!mayUploadFile) {
        if (publicIdea) {
            mayUploadFile = ideaPermissionChecker.isHasPermissionAddDocumentPublic();
        } else {
            mayUploadFile = ideaPermissionChecker.isHasPermissionAddDocumentPrivate();
        }
    }

    if (mayUploadFile) {
        response.setRenderParameter("urlTitle", urlTitle);

        PortletFileUpload p = new PortletFileUpload();

        try {
            FileItemIterator itemIterator = p.getItemIterator(request);

            while (itemIterator.hasNext()) {
                FileItemStream fileItemStream = itemIterator.next();

                if (fileItemStream.getFieldName().equals("file")) {

                    InputStream is = fileItemStream.openStream();
                    BufferedInputStream bis = new BufferedInputStream(is);

                    String fileName = fileItemStream.getName();
                    String contentType = fileItemStream.getContentType();

                    ideaService.uploadFile(idea, publicIdea, fileName, contentType, bis);
                }
            }
        } catch (FileUploadException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (IOException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (se.vgregion.service.innovationsslussen.exception.FileUploadException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (RuntimeException e) {
            Throwable lastCause = Util.getLastCause(e);
            if (lastCause instanceof SQLException) {
                SQLException nextException = ((SQLException) lastCause).getNextException();
                if (nextException != null) {
                    LOGGER.error(nextException.getMessage(), nextException);
                }
            }
        } finally {
            response.setRenderParameter("ideaType", fileType);
        }
    } else {
        throw new FileUploadException("The user is not authorized to upload to this idea instance.");
    }

    response.setRenderParameter("urlTitle", urlTitle);
    response.setRenderParameter("type", fileType);
    response.setRenderParameter("showView", "showIdea");
}

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 {//from ww  w. j ava  2  s.  com
        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;/* ww  w  .  j a v a  2 s . com*/
    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   w  w  w. ja  v  a  2s .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);
}