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:edu.byui.fb.AddImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w  ww  .j  ava 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 {
    // Get the DataBaseHandler
    DataBaseHandler dbh = DataBaseHandler.getInstance();

    // Get information about the user currently logged in
    boolean logged = (boolean) request.getSession().getAttribute("logged");
    String username = (String) request.getSession().getAttribute("username");
    User user = dbh.getUser(username);

    // Are we currently logged in
    if (username != null && user != null && logged) {
        // Check to make sure the request is multipart
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                // Parse the request into FileItems
                List<FileItem> multipart = new ServletFileUpload(new DiskFileItemFactory())
                        .parseRequest(request);
                String title = "";
                InputStream imageInputStream = null;

                // Loop through each item
                for (FileItem item : multipart) {
                    // Are we dealing with a file or something different
                    if (!item.isFormField()) {
                        if (item.getFieldName().equals("image")) {
                            imageInputStream = item.getInputStream();
                        }
                    } else if (item.isFormField()) {
                        if (item.getFieldName().equals("title")) {
                            title = item.getString();
                        }
                    }
                }

                // Was there a title? If not, give a fake title
                if (title.equals("")) {
                    title = "No title";
                }

                // Set up the image and add to the DataBase.
                Image image = new Image(title, imageInputStream);
                dbh.addImage(image, user);
                request.setAttribute("imageAdded", true);
            } catch (FileUploadException ex) {
                Logger.getLogger(AddImage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } else {
        // Was there an error?
        request.setAttribute("addedError", true);
    }

    // Go to admin.jsp
    request.getRequestDispatcher("LoadImages?dest=admin.jsp").forward(request, response);
}

From source file:com.lock.unlockInfo.servlet.SubmitUnlockImg.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpResponseModel responseModel = new HttpResponseModel();
    try {/*  w  w  w .j  ava2s.  co  m*/
        boolean isMultipart = ServletFileUpload.isMultipartContent(request); // ???
        if (isMultipart) {
            Hashtable<String, String> htSubmitParam = new Hashtable<String, String>(); // ??
            List<String> fileList = new ArrayList<String>();// 

            // DiskFileItemFactory??
            // ????List
            // list???
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = iterator.next();
                if (item.isFormField()) {
                    // ?
                    String sFieldName = item.getFieldName();
                    String sFieldValue = item.getString("UTF-8");
                    htSubmitParam.put(sFieldName, sFieldValue);
                } else {
                    // ,???
                    String newFileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString()
                            + ".jpg";
                    File filePath = new File(
                            getServletConfig().getServletContext().getRealPath(Constants.File_Upload));
                    if (!filePath.exists()) {
                        filePath.mkdirs();
                    }
                    File file = new File(filePath, newFileName);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //?
                    BufferedInputStream bis = new BufferedInputStream(item.getInputStream());
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                    byte[] b = new byte[1024];
                    int length = 0;
                    while ((length = bis.read(b)) > 0) {
                        bos.write(b, 0, length);
                    }
                    bos.close();
                    bis.close();
                    //?url
                    String fileUrl = request.getRequestURL().toString();
                    fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("/")); //?URL
                    fileUrl = fileUrl + Constants.File_Upload + "/" + newFileName;
                    /**/
                    fileList.add(fileUrl);
                }
            }

            //
            String unlockInfoId = htSubmitParam.get("UnlockInfoId");
            String imgType = htSubmitParam.get("ImgType");
            String newFileUrl = fileList.get(0);

            UnlockInfoService unlockInfoService = (UnlockInfoService) context.getBean("unlockInfoService");
            UnlockInfo unlockInfo = unlockInfoService.queryByPK(Long.valueOf(unlockInfoId));
            if (imgType.equals("customerIdImg")) {
                unlockInfo.setCustomerIdImg(newFileUrl);
            } else if (imgType.equals("customerDrivingLicenseImg")) {
                unlockInfo.setCustomerDrivingLicenseImg(newFileUrl);
            } else if (imgType.equals("customerVehicleLicenseImg")) {
                unlockInfo.setCustomerVehicleLicenseImg(newFileUrl);
            } else if (imgType.equals("customerBusinessLicenseImg")) {
                unlockInfo.setCustomerBusinessLicenseImg(newFileUrl);
            } else if (imgType.equals("customerIntroductionLetterImg")) {
                unlockInfo.setCustomerIntroductionLetterImg(newFileUrl);
            } else if (imgType.equals("unlockWorkOrderImg")) {
                unlockInfo.setUnlockWorkOrderImg(newFileUrl);
            }
            /**/
            unlockInfoService.update(unlockInfo);
        }
    } catch (Exception e) {
        e.printStackTrace();
        responseModel.responseCode = "0";
        responseModel.responseMessage = e.toString();
    }
    /* ??? */
    response.setHeader("content-type", "text/json;charset=utf-8");
    response.getOutputStream().write(responseModel.toByteArray());
}

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 . java  2 s  . c  o  m
            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:com.silverpeas.form.displayers.CheckBoxDisplayer.java

@Override
public List<String> update(List<FileItem> items, TextField field, FieldTemplate template,
        PagesContext pageContext) throws FormException {
    SilverTrace.debug("form", "AbstractForm.getParameterValues", "root.MSG_GEN_ENTER_METHOD",
            "parameterName = " + template.getFieldName());
    String value = "";
    Iterator<FileItem> iter = items.iterator();
    String parameterName = template.getFieldName();
    while (iter.hasNext()) {
        FileItem item = iter.next();
        if (parameterName.equals(item.getFieldName())) {
            value += item.getString();//from   w  w w  .  j  a  v a 2 s.  c  o m
            if (iter.hasNext()) {
                value += "##";
            }
        }
    }
    SilverTrace.debug("form", "AbstractForm.getParameterValues", "root.MSG_GEN_EXIT_METHOD",
            "parameterValue = " + value);
    if (pageContext.getUpdatePolicy() == PagesContext.ON_UPDATE_IGNORE_EMPTY_VALUES
            && !StringUtil.isDefined(value)) {
        return new ArrayList<String>();
    }
    return update(value, field, template, pageContext);
}

From source file:hd.controller.AddImageToProjectServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w  w  w. j  a  va  2s .  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 {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) { //to do
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iter = items.iterator();
            Hashtable params = new Hashtable();
            String fileName = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString("UTF-8"));
                } else if (!item.isFormField()) {
                    try {
                        long time = System.currentTimeMillis();
                        String itemName = item.getName();
                        fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1);
                        String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName;
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName;
                        //                            savedFile = new File(localPath);
                        //                            item.write(savedFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            //Init Jpa
            CategoryJpaController categoryJpa = new CategoryJpaController(emf);
            StyleJpaController styleJpa = new StyleJpaController(emf);
            ProjectJpaController projectJpa = new ProjectJpaController(emf);
            IdeaBookPhotoJpaController photoJpa = new IdeaBookPhotoJpaController(emf);
            // get Object Category by categoryId
            int cateId = Integer.parseInt((String) params.get("ddlCategory"));
            Category cate = categoryJpa.findCategory(cateId);
            // get Object Style by styleId
            int styleId = Integer.parseInt((String) params.get("ddlStyle"));
            Style style = styleJpa.findStyle(styleId);
            // get Object Project by projectId
            int projectId = Integer.parseInt((String) params.get("txtProjectId"));
            Project project = projectJpa.findProject(projectId);
            project.setStatus(Constant.STATUS_WAIT);
            projectJpa.edit(project);
            //Get param
            String title = (String) params.get("title");
            String description = (String) params.get("description");

            String url = "images/" + fileName;
            //Init IdeabookPhoto
            IdeaBookPhoto photo = new IdeaBookPhoto(title, url, description, cate, style, project);
            photoJpa.create(photo);
            url = "ViewMyProjectDetailServlet?txtProjectId=" + projectId;

            //System
            HDSystem system = new HDSystem();
            system.setNotificationProject(request);
            response.sendRedirect(url);
        }
    } catch (Exception e) {
        log("Error at AddImageToProjectServlet: " + e.getMessage());
    } finally {
        out.close();
    }
}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.CommonsFileUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    log("Content-Type: " + request.getContentType());

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*/*from  www.  ja  va  2  s.  c  om*/
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(10 * 1024 * 1024); //10 MB
    /*
    * Set the temporary directory to store the uploaded files of size above threshold.
    */
    fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
        List items = uploadHandler.parseRequest(request);
        log("FileItems: " + items.toString());
        Iterator itr = items.iterator();
        while (itr.hasNext()) {

            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if (item.isFormField()) {
                out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
            } else {
                //Handle Uploaded files.
                out.println("<html><head><title>CommonsFileUploadServlet</title></head><body><p>");
                out.println("Field Name = " + item.getFieldName() + "\nFile Name = " + item.getName()
                        + "\nContent type = " + item.getContentType() + "\nFile Size = " + item.getSize());
                out.println("</p>");
                out.println("<img src=\"" + request.getContextPath() + "/files/" + item.getName() + "\"/>");
                out.println("</body></html>");
                /*
                 * Write file to the ultimate location.
                 */
                File file = new File(destinationDir, item.getName());
                item.write(file);
            }
            out.close();
        }
    } catch (FileUploadException ex) {
        log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }
}

From source file:com.duroty.application.mail.actions.SaveDraftAction.java

protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionMessages errors = new ActionMessages();

    try {/*  w  w w.  j  a va  2s  . c om*/
        boolean isMultipart = FileUpload.isMultipartContent(request);

        if (isMultipart) {
            Map fields = new HashMap();
            Vector attachments = new Vector();

            //Parse the request
            List items = diskFileUpload.parseRequest(request);

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

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.isFormField()) {
                    fields.put(item.getFieldName(), item.getString());
                } else {
                    if (!StringUtils.isBlank(item.getName())) {
                        ByteArrayOutputStream baos = null;

                        try {
                            baos = new ByteArrayOutputStream();

                            IOUtils.copy(item.getInputStream(), baos);

                            MailPartObj part = new MailPartObj();
                            part.setAttachent(baos.toByteArray());
                            part.setContentType(item.getContentType());
                            part.setName(item.getName());
                            part.setSize(item.getSize());

                            attachments.addElement(part);
                        } catch (Exception ex) {
                        } finally {
                            IOUtils.closeQuietly(baos);
                        }
                    }
                }
            }

            String body = "";

            if (fields.get("taBody") != null) {
                body = (String) fields.get("taBody");
            } else if (fields.get("taReplyBody") != null) {
                body = (String) fields.get("taReplyBody");
            }

            Preferences preferencesInstance = getPreferencesInstance(request);

            Send sendInstance = getSendInstance(request);

            String mid = (String) fields.get("mid");

            sendInstance.saveDraft(mid, Integer.parseInt((String) fields.get("identity")),
                    (String) fields.get("to"), (String) fields.get("cc"), (String) fields.get("bcc"),
                    (String) fields.get("subject"), body, attachments,
                    preferencesInstance.getPreferences().isHtmlMessage(),
                    Charset.defaultCharset().displayName(), (String) fields.get("priority"));
        } else {
            errors.add("general",
                    new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null"));
            request.setAttribute("exception", "The form is null");
            request.setAttribute("newLocation", null);
            doTrace(request, DLog.ERROR, getClass(), "The form is null");
        }
    } catch (Exception ex) {
        String errorMessage = ExceptionUtilities.parseMessage(ex);

        if (errorMessage == null) {
            errorMessage = "NullPointerException";
        }

        errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage));
        request.setAttribute("exception", errorMessage);
        doTrace(request, DLog.ERROR, getClass(), errorMessage);
    } finally {
    }

    if (errors.isEmpty()) {
        doTrace(request, DLog.INFO, getClass(), "OK");

        return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD);
    } else {
        saveErrors(request, errors);

        return mapping.findForward(Constants.ACTION_FAIL_FORWARD);
    }
}

From source file:net.jforum.core.support.vraptor.DefaultLogicLocator.java

@SuppressWarnings({ "deprecation", "unchecked" })
private void handleMultipartRequest(VRaptorServletRequest servletRequest) {
    if (!FileUploadBase.isMultipartContent(servletRequest)) {
        return;/*from   w  w  w.j a va 2s .  c  om*/
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory(4096 * 16, this.temporaryDirectory);

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

    List<FileItem> fileItems;

    // assume we know there are two files. The first file is a small
    // text file, the second is unknown and is written to a file on
    // the server
    try {
        fileItems = upload.parseRequest(servletRequest);
    } catch (FileUploadException e) {
        logger.warn("There was some problem parsing this multipart request, or someone is not sending a "
                + "RFC1867 compatible multipart request.", e);
        return;
    }

    for (FileItem item : fileItems) {
        if (item.isFormField()) {
            servletRequest.addParameterValue(item.getFieldName(), item.getString());
        } else {
            if (!item.getName().trim().equals("")) {
                try {
                    File file = File.createTempFile("vraptor.", ".upload");
                    item.write(file);

                    UploadedFileInformation fileInformation = new BasicUploadedFileInformation(file,
                            item.getName(), item.getContentType());

                    this.registeUploadedFile(servletRequest, item.getFieldName(), fileInformation);
                } catch (Exception e) {
                    logger.error("Nasty uploaded file " + item.getName(), e);
                }
            } else {
                logger.debug("A file field was empy: " + item.getFieldName());
            }
        }
    }
}

From source file:edu.um.umflix.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HashMap<String, String> mapValues = new HashMap<String, String>();
    List<Clip> clips = new ArrayList<Clip>();
    List<Byte[]> listData = new ArrayList<Byte[]>();
    int i = 0;//from  w  w  w. j a  v  a  2  s . c o  m

    try {
        List<FileItem> items = getFileItems(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process normal fields here.

                mapValues.put(item.getFieldName(), item.getString());
                // w.print("Field name: " + item.getFieldName());
                // w.print("Field value: " + item.getString());
            } else {
                // Process <input type="file"> here.

                InputStream movie = item.getInputStream();
                byte[] bytes = IOUtils.toByteArray(movie);
                Byte[] clipBytes = ArrayUtils.toObject(bytes);
                Clip clip = new Clip(Long.valueOf(0), i);
                clips.add(i, clip);
                listData.add(i, clipBytes);
                i++;
                // w.print(movie);

            }
        }
    } catch (FileUploadException e) {
        log.error("Error uploading file, please try again.");
        request.setAttribute("error", "Error uploading file, please try again");
        request.setAttribute("token", mapValues.get("token"));
        request.getRequestDispatcher("/upload.jsp").forward(request, response);
    }
    //Sets duration of clip and saves clipdata
    for (int j = 0; j < clips.size(); j++) {
        int duration = timeToInt(mapValues.get("clipduration" + j));
        clips.get(j).setDuration(Long.valueOf(duration));
        ClipData clipData = new ClipData(listData.get(j), clips.get(j));

        try {
            vManager.uploadClip(mapValues.get("token"), new Role(Role.RoleType.MOVIE_PROVIDER.getRole()),
                    clipData);
            log.info("ClipData uploader!");
        } catch (InvalidTokenException e) {
            log.error("Unknown user, please try again.");
            request.setAttribute("error", "Unknown user, please try again.");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

    }

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Date endDate = null;
    Date startDate = null;
    Date premiereDate = null;
    try {
        endDate = formatter.parse(mapValues.get("endDate"));
        startDate = formatter.parse(mapValues.get("startDate"));
        premiereDate = formatter.parse(mapValues.get("premiere"));
    } catch (ParseException e) {
        log.error("Error parsing date");
        request.setAttribute("token", mapValues.get("token"));
        request.setAttribute("error", "Invalid date, please try again");
        request.getRequestDispatcher("/upload.jsp").forward(request, response);
        return;

    }

    License license = new License(false, Long.valueOf(0), mapValues.get("licenseDescription"), endDate,
            Long.valueOf(mapValues.get("maxViews")), Long.valueOf(1), startDate, mapValues.get("licenseName"));
    List<License> licenses = new ArrayList<License>();
    licenses.add(license);

    ArrayList<String> cast = new ArrayList<String>();
    cast.add(mapValues.get("actor"));
    Movie movie = new Movie(cast, clips, mapValues.get("director"), Long.valueOf(mapValues.get("duration")),
            false, mapValues.get("genre"), licenses, premiereDate, mapValues.get("title"));

    try {
        vManager.uploadMovie(mapValues.get("token"), new Role(Role.RoleType.MOVIE_PROVIDER.getRole()), movie);
        log.info("Movie uploaded!");
    } catch (InvalidTokenException e) {
        log.error("Unknown user, please try again.");
        request.setAttribute("error", "Unknown user, please try again.");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
        return;
    }
    request.setAttribute("message", "Movie uploaded successfully.");
    request.setAttribute("token", mapValues.get("token"));
    request.getRequestDispatcher("/upload.jsp").forward(request, response);
}

From source file:ca.myewb.frame.PostParamWrapper.java

public PostParamWrapper(HttpServletRequest request) throws Exception {
    if (!FileUpload.isMultipartContent(request)) {
        return;//from  www . j a  v  a 2 s . c  o  m
    }

    DiskFileUpload upload = new DiskFileUpload();
    upload.setRepositoryPath(Helpers.getUserFilesDir() + "/temp");

    try {
        List items = upload.parseRequest(request);

        Iterator iter = items.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                stringParams.put(item.getFieldName(), item.getString());
                allParams.put(item.getFieldName(), item);
            } else if (item.getSize() > 0) {
                fileParams.put(item.getFieldName(), item);
                allParams.put(item.getFieldName(), item);
            }
        }
    } catch (FileUploadException ex) {
        log.debug("The file upload exception returned the message: " + ex.getMessage());
        // Usually means user cancelled upload and connection timed out.
        // Do nothing.
    }
}