Example usage for org.apache.commons.fileupload FileItemStream getName

List of usage examples for org.apache.commons.fileupload FileItemStream getName

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream getName.

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

From source file:Project.FileUploadServlet.java

public static boolean processFile(String path, FileItemStream item) {
    try {//from  ww w  .j a  v  a 2  s  .c  om
        File f = new File(path + File.separator + "images");
        if (!f.exists()) {
            f.mkdir();
        }
        File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
        FileOutputStream fos = new FileOutputStream(savedFile);
        InputStream is = item.openStream();
        int x = 0;
        byte[] b = new byte[1024];
        while ((x = is.read(b)) != -1) {
            fos.write(b, 0, x);
        }
        fos.flush();
        fos.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:rurales.FileUploadRural.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w  ww .  j  a v a  2s . 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 {
    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.//from w w w . ja  v  a  2 s . co  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   www.  j a va 2s . c o  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:us.mn.state.health.lims.analyzerimport.action.AnalyzerImportServlet.java

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

    String password = null;/* w  ww.ja  va2s. c  o 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 ww.  j  a  va2 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());
    }
}