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:com.manning.cmis.theblend.servlets.AddServlet.java

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

    // check for multipart content
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        // we expected content -> return to add page
        dispatch("add.jsp", "Add something new. The Blend.", request, response);
    }/*from w w w .j  ava 2 s  .  c  o m*/

    Map<String, Object> properties = new HashMap<String, Object>();
    File uploadedFile = null;
    String parentId = null;
    String parentPath = null;
    ObjectId newId = null;

    // process the request
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(50 * 1024 * 1024);

        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);

        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

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

                if (PARAM_PARENT_ID.equalsIgnoreCase(name)) {
                    parentId = item.getString();
                } else if (PARAM_PARENT_PATH.equalsIgnoreCase(name)) {
                    parentPath = item.getString();
                } else if (PARAM_TYPE_ID.equalsIgnoreCase(name)) {
                    properties.put(PropertyIds.OBJECT_TYPE_ID, item.getString());
                }
            } else {
                String name = item.getName();
                if (name == null) {
                    name = "file";
                } else {
                    // if the browser provided a path instead of a file name,
                    // strip off the path
                    int x = name.lastIndexOf('/');
                    if (x > -1) {
                        name = name.substring(x + 1);
                    }
                    x = name.lastIndexOf('\\');
                    if (x > -1) {
                        name = name.substring(x + 1);
                    }

                    name = name.trim();
                    if (name.length() == 0) {
                        name = "file";
                    }
                }

                properties.put(PropertyIds.NAME, name);

                uploadedFile = File.createTempFile("blend", "tmp");
                item.write(uploadedFile);
            }
        }
    } catch (Exception e) {
        throw new TheBlendException("Upload failed: " + e, e);
    }

    if (uploadedFile == null) {
        throw new TheBlendException("No content!");
    }

    try {
        // prepare the content stream
        ContentStream contentStream = null;
        try {
            String objectTypeId = (String) properties.get(PropertyIds.OBJECT_TYPE_ID);
            contentStream = prepareContentStream(session, uploadedFile, objectTypeId, properties);
        } catch (Exception e) {
            throw new TheBlendException("Upload failed: " + e, e);
        }

        // find the parent folder
        // (we don't deal with unfiled documents here)
        Folder parent = null;
        if (parentId != null) {
            parent = CMISHelper.getFolder(session, parentId, CMISHelper.LIGHT_OPERATION_CONTEXT,
                    "parent folder");
        } else {
            parent = CMISHelper.getFolderByPath(session, parentPath, CMISHelper.LIGHT_OPERATION_CONTEXT,
                    "parent folder");
        }

        // create the document
        try {
            newId = session.createDocument(properties, parent, contentStream, null);
        } catch (CmisBaseException cbe) {
            throw new TheBlendException("Could not create document: " + cbe.getMessage(), cbe);
        } finally {
            try {
                contentStream.getStream().close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    } finally {
        // delete temp file
        uploadedFile.delete();
    }

    // show the newly created document
    redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response);
}

From source file:MyPack.AddAuctionItems.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//ww w.  j a  v a 2 s .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 {
    config = getServletConfig();
    System.out.println("Inside insert code");
    try {

        session = request.getSession();
        int regid = (Integer) session.getAttribute("regid");
        String itemname = "";
        int itemprice = 0;
        String date = "";
        String time = "";
        int catid = 0;
        String itempic = "";

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException ex) {
                Logger.getLogger(AddAuctionItems.class.getName()).log(Level.SEVERE, null, ex);
            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString();
                    if (name.equals("itemname")) {
                        itemname = value;
                        //                      count1=1;
                        System.out.println("name = " + itemname);
                    }
                    if (name.equals("itemprice")) {
                        itemprice = Integer.parseInt(value);
                        //                         count2=2;
                        System.out.println("price = " + itemprice);
                    }
                    if (name.equals("itemdate")) {
                        date = value;
                        //                         count5=5;
                        System.out.println("date = " + date);
                    }
                    if (name.equals("itemtime")) {
                        time = value;
                        // count3=3;
                        System.out.println("time = " + time);
                    }

                    if (name.equals("selectedRecord")) {
                        //                     count4=4;
                        catid = Integer.parseInt(value);
                        System.out.println("emp_emailid = " + catid);
                    }

                } else {
                    try {

                        itempic = item.getName();
                        System.out.println("itemName============" + itempic);
                        File savedFile = new File(
                                config.getServletContext().getRealPath("/") + "../../web/upimage\\" + itempic);
                        //                            System.out.println(config.getServletContext().getRealPath("/") + "upimage\\" + itempic);
                        item.write(savedFile);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        PrintWriter out = response.getWriter();
        DBConnection Db = new DBConnection();
        String sql = "insert into tb_auction_items values(null,'" + itemname + "','" + itemprice + "','" + date
                + "','" + time + "','0','" + catid + "','" + regid + "','" + itempic + "')";
        System.out.println(sql);
        int row = Db.UpdateQuery(sql);
        if (row > 0) {
            out.print("<script>alert('Successulyy added');</script>");
            response.sendRedirect("viewitems");
            // request.getRequestDispatcher("viewitems").include(request, response);

        } else {
            request.getRequestDispatcher("AddAuctionItemss.jsp").forward(request, response);
            out.print("<script>alert('Failed to Update');</script>");
        }
        Db.Close();
    } catch (Exception ex) {
        Logger.getLogger(AddAuctionItems.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Controller.ControllerCustomers.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// w w w.  j  av 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 {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception 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());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    String username = (String) params.get("txtusername");
                    String password = (String) params.get("txtpassword");
                    String hoten = (String) params.get("txthoten");
                    String gioitinh = (String) params.get("txtgioitinh");
                    String email = (String) params.get("txtemail");
                    String role = (String) params.get("txtrole");
                    String anh = (String) params.get("txtanh");
                    //Update  product
                    if (fileName.equals("")) {

                        Customer Cus = new Customer(username, password, hoten, gioitinh, email, role, anh);
                        CustomerDAO.SuaThongTinKhachHang(Cus);
                        RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                        rd.forward(request, response);

                    } else {
                        // bat dau ghi file
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        //ket thuc ghi

                        Customer Cus = new Customer(username, password, hoten, gioitinh, email, role,
                                "upload\\" + fileName);
                        CustomerDAO.SuaThongTinKhachHang(Cus);

                        RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                        rd.forward(request, response);
                    }

                } catch (Exception e) {
                    System.out.println(e);
                    RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp");
                    rd.forward(request, response);
                }
            }

        }
    }

}

From source file:com.xclinical.mdr.server.DocumentServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    try {//w  ww.j  a  va 2  s  .com
        if (ServletFileUpload.isMultipartContent(req)) {
            log.debug("detected multipart content");

            final FileInfo info = new FileInfo();

            ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());

            @SuppressWarnings("unchecked")
            List<FileItem> items = fileUpload.parseRequest(req);

            String session = null;

            for (Iterator<FileItem> i = items.iterator(); i.hasNext();) {
                log.debug("detected form field");

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

                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();

                    if (fieldName != null) {
                        log.debug("{0}={1}", fieldName, fieldValue);
                    } else {
                        log.severe("fieldName may not be null");
                    }

                    if ("session".equals(fieldName)) {
                        session = fieldValue;
                    }
                } else {
                    log.debug("detected content");

                    info.contentName = item.getName();
                    info.contentName = new File(info.contentName).getName();
                    info.contentType = item.getContentType();
                    info.content = item.get();

                    log.debug("{0} bytes", info.content.length);
                }
            }

            if (info.content == null)
                throw new IllegalArgumentException("there is no content");
            if (info.contentType == null)
                throw new IllegalArgumentException("There is no content type");
            if (info.contentName == null)
                throw new IllegalArgumentException("There is no content name");

            Session.runInSession(session, new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Document document = Document.create(info.contentName, info.contentType, info.content);

                    log.info("Created document " + document.getId());

                    ReferenceDocument referenceDocument = saveFile(req, document);

                    JsonCommandServlet.writeResponse(resp, FlatJsonExporter.of(referenceDocument));
                    return null;
                }
            });
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    } catch (FileUploadException e) {
        log.severe(e);
        throw new ServletException(e);
    } catch (Exception e) {
        log.severe(e);
        throw new ServletException(e);
    }
}

From source file:it.biblio.servlets.Inserimento_pub.java

/**
 * metodo per gestire l'upload di file e inserimento pubblicazione con prima
 * ristampa/*from w  w w  . ja  v  a2 s . co m*/
 *
 * @param request
 * @param response
 * @param k
 * @return
 * @throws IOException
 */
private boolean upload(HttpServletRequest request) throws IOException, Exception {

    Map<String, Object> pub = new HashMap<String, Object>();
    Map<String, Object> ristampe = new HashMap<String, Object>();
    Map<String, Object> keyword = new HashMap<String, Object>();
    HttpSession s = SecurityLayer.checkSession(request);
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfo = new ServletFileUpload(fif);
        List<FileItem> items = sfo.parseRequest(request);
        for (FileItem item : items) {
            String fname = item.getFieldName();
            if (item.isFormField() && fname.equals("titolo") && !item.getString().isEmpty()) {
                pub.put("titolo", item.getString());
                pub.put("utente", s.getAttribute("userid"));
            } else if (item.isFormField() && fname.equals("descrizione") && !item.getString().isEmpty()) {
                pub.put("descrizione", item.getString());
            } else if (item.isFormField() && fname.equals("autore") && !item.getString().isEmpty()) {
                pub.put("autore", item.getString());

            } else if (item.isFormField() && fname.equals("categoria") && !item.getString().isEmpty()) {
                pub.put("categoria", item.getString());

            } else if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) {
                ristampe.put("numpagine", Integer.parseInt(item.getString()));
            } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) {
                ristampe.put("datapub", item.getString());
            } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) {
                ristampe.put("editore", item.getString());
            } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) {
                ristampe.put("lingua", item.getString());
            } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) {
                ristampe.put("indice", item.getString());
            } else if (item.isFormField() && fname.equals("keyword") && !item.getString().isEmpty()) {
                keyword.put("tag1", item.getString());
            } else if (item.isFormField() && fname.equals("keyword2") && !item.getString().isEmpty()) {
                keyword.put("tag2", item.getString());
            } else if (item.isFormField() && fname.equals("keyword3") && !item.getString().isEmpty()) {
                keyword.put("tag3", item.getString());
            } else if (!item.isFormField() && fname.equals("PDF")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF"
                            + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("download", "PDF" + File.separatorChar + name);
                }
            } else if (!item.isFormField() && fname.equals("copertina")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar
                            + "Copertine" + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("copertina", "Copertine" + File.separatorChar + name);
                }
            }
        }

        Database.insertRecord("keyword", keyword);
        ResultSet ss = Database.selectRecord("keyword", "tag1='" + keyword.get("tag1") + "' && " + "tag2='"
                + keyword.get("tag2") + "' && tag3='" + keyword.get("tag3") + "'");
        if (!isNull(ss)) {
            int indicek = 0;
            while (ss.next()) {
                indicek = ss.getInt("id");
            }
            pub.put("keyword", indicek);
            Database.insertRecord("pubblicazioni", pub);
            ResultSet rs = Database.selectRecord("pubblicazioni", "titolo='" + pub.get("titolo") + "'");
            while (rs.next()) {
                ristampe.put("pubblicazioni", rs.getInt("id"));
            }
            return Database.insertRecord("ristampe", ristampe);
        } else {
            return false;
        }

    }
    return false;
}

From source file:com.college.AddAdditionalMarksheet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w . j av a2 s. c  om*/
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

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

        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
        ps = con.prepareStatement("insert into certificate (studentId, certificate) values (?,?)");

        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload sfu = new ServletFileUpload(factory);
        List items = sfu.parseRequest(request);

        Iterator iter = items.iterator();
        byte[] certificate = null;

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

            byte[] blobValue = item.get();
            if (blobValue != null && blobValue.length > 0) {
                String fieldName = item.getFieldName();

                if (!item.isFormField()) { //This if clause is for images.
                    if ("certificate".equalsIgnoreCase(fieldName)) {
                        certificate = blobValue;
                    }

                    // you can add more clauses here.
                } else { // This else clause if for other fields.
                    String fieldValue = new String(blobValue);
                    if (item.getFieldName() != null) {
                        if ("studentId".equalsIgnoreCase(fieldName)) {
                            studentId = fieldValue;
                        } else if ("studentName".equalsIgnoreCase(fieldName)) {
                            studentName = fieldValue;
                        }

                        // add more fields here.
                    }
                }
            }
        }

        ps.setString(1, studentId);
        ps.setBytes(2, certificate);

        int i = ps.executeUpdate();
        if (i != 0) {
            out.println("Success");
            response.sendRedirect(
                    "additionalMarksheetForm.jsp?studentName=" + studentName + "&studentId=" + studentId);
            out.println("Success");
        } else {
            out.println("Failed");
        }
    } catch (Exception ex) {
        out.println(ex);
    } finally {
        out.close();
    }
}

From source file:com.controller.changeLogo.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w w . ja v a 2  s.co  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
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    getSqlMethodsInstance().session = request.getSession();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, uploadType = null;
    RequestDispatcher request_dispatcher = null;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        uploadPath = AppConstants.USER_LOGO;

        // Verify the content type
        String contentType = request.getContentType();

        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

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

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

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("upload")) {
                        uploadType = fi.getString();
                    }

                } else {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    Integer UID = (Integer) getSqlMethodsInstance().session.getAttribute("UID");

                    uploadPath = uploadPath + File.separator + UID + File.separator + "logo";

                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }

                    //                                int inStr = fileName.indexOf(".");
                    //                                String Str = fileName.substring(0, inStr);
                    //
                    //                                fileName = Str + "_" + UID + ".jpeg";
                    fileName = fileName + "_" + UID;
                    getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName);
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    if (uploadType.equals("update")) {
                        String file_name_to_delete = getSqlMethodsInstance().getLogofileName(UID);
                        String filePath_to_delete = uploadPath + File.separator + file_name_to_delete;

                        File deletefile = new File(filePath_to_delete);
                        deletefile.delete();
                    }

                    filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);
                    fi.write(storeFile);

                    getSqlMethodsInstance().updateUsers(UID, fileName);
                    out.println("Uploaded Filename: " + filePath + "<br>");

                    response.sendRedirect(request.getContextPath() + "/settings.jsp");

                }

            }
        }

    } catch (Exception ex) {
        logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));

        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
        getSqlMethodsInstance().closeConnection();
    }

}

From source file:com.skin.generator.action.UploadTestAction.java

/**
 * @param request//from www .  ja v  a  2  s.  com
 * @return Map<String, Object>
 * @throws Exception
 */
public Map<String, Object> parse(HttpServletRequest request) throws Exception {
    String repository = System.getProperty("java.io.tmpdir");
    int maxFileSize = 1024 * 1024 * 1024;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(new File(repository));
    factory.setSizeThreshold(1024 * 1024);
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
    servletFileUpload.setFileSizeMax(maxFileSize);
    servletFileUpload.setSizeMax(maxFileSize);
    Map<String, Object> map = new HashMap<String, Object>();
    List<?> list = servletFileUpload.parseRequest(request);

    if (list != null && list.size() > 0) {
        for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
            FileItem item = (FileItem) iterator.next();

            if (item.isFormField()) {
                logger.debug("form field: {}, {}", item.getFieldName(), item.toString());
                map.put(item.getFieldName(), item.getString("utf-8"));
            } else {
                logger.debug("file field: {}", item.getFieldName());
                map.put(item.getFieldName(), item);
            }
        }
    }
    return map;
}

From source file:it.lufraproini.cms.servlet.upload_user_img.java

private Map prendiInfoFile(HttpServletRequest request) throws ErroreGrave, IOException {
    Map infofile = new HashMap();
    //riutilizzo codice prof. Della Penna per l'upload
    if (ServletFileUpload.isMultipartContent(request)) {
        // Funzioni delle librerie Apache per l'upload
        try {//  w  w  w.  j  a v  a  2 s .co m
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items;
            FileItem file = null;

            items = upload.parseRequest(request);
            for (FileItem item : items) {
                String name = item.getFieldName();
                if (name.equals("file_to_upload")) {
                    file = item;
                    break;
                }
            }
            if (file == null || file.getName().equals("")) {
                throw new ErroreGrave("la form non ha inviato il campo file!");
            } else {
                //informazioni
                String nome_e_path = file.getName();
                String estensione = FilenameUtils.getExtension(FilenameUtils.getName(nome_e_path));
                String nome_senza_estensione = FilenameUtils.getBaseName(FilenameUtils.getName(nome_e_path));
                infofile.put("nome_completo", nome_senza_estensione + "." + estensione);
                infofile.put("estensione", estensione);
                infofile.put("nome_senza_estensione", nome_senza_estensione);
                infofile.put("dimensione", file.getSize());
                infofile.put("input_stream", file.getInputStream());
                infofile.put("content_type", file.getContentType());
            }

        } catch (FileUploadException ex) {
            Logger.getLogger(upload_user_img.class.getName()).log(Level.SEVERE, null, ex);
            throw new ErroreGrave("errore libreria apache!");
        }

    }
    return infofile;
}

From source file:com.sr.controller.MahasiswaController.java

@RequestMapping(value = "/isibiodata", method = { RequestMethod.GET, RequestMethod.POST })
public String isi(HttpServletRequest request) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(factory);
    try {//ww w.  j a va 2s. c om
        List<FileItem> items = sfu.parseRequest(request);
        FileItem foto = items.get(0);
        FileItem nama_lengkap = items.get(1);
        FileItem tempat_lahir = items.get(2);
        FileItem tanggal_lahir = items.get(3);
        FileItem agama = items.get(4);
        FileItem kelamin = items.get(5);
        FileItem alamat_asal = items.get(6);
        FileItem kabupaten = items.get(7);
        FileItem provinsi = items.get(8);
        FileItem no_telp = items.get(9);
        FileItem nama_ayah = items.get(10);
        FileItem nama_ibu = items.get(11);
        FileItem pend_ayah = items.get(12);
        FileItem pend_ibu = items.get(13);
        FileItem pekerjaan_ayah = items.get(14);
        FileItem pekerjaan_ibu = items.get(15);
        FileItem pendapatan_ortu = items.get(16);
        FileItem no_telp_rumah = items.get(17);
        FileItem no_telp_hp = items.get(18);
        FileItem alamat_keluarga_terdekat = items.get(19);
        FileItem no_telp_rumah_terdekat = items.get(20);
        FileItem no_telp_hp_terdekat = items.get(21);
        FileItem nim = items.get(22);
        FileItem prodi = items.get(23);
        FileItem jurusan = items.get(24);
        FileItem fakultas = items.get(25);
        FileItem semester = items.get(26);
        FileItem ipk_sr = items.get(27);
        FileItem rapor_smu = items.get(28);

        for (FileItem item : items) {
            if (item.isFormField()) {
                System.out.println("FieldName: " + item.getFieldName() + " value: " + item.getString());
            }
        }

        List<Prestasi> prestasi = new ArrayList();
        for (int i = 29; i < items.size() - 1; i += 2) {
            FileItem n = items.get(i);
            FileItem k = items.get(i + 1);
            Prestasi pres = new Prestasi();
            pres.setNim(nim.getString());
            pres.setNo_sertifikat(n.getString());
            pres.setNama_prestasi(k.getString());
            if (k.get() != null) {
                if (n.getFieldName().equals("sertifikatkegiatan")) {
                    pres.setJenis_prestasi("Kampus");
                    prestasi.add(pres);
                } else {
                    pres.setJenis_prestasi("Luar Kampus");
                    prestasi.add(pres);
                }
            }
        }

        Mahasiswa maha = new Mahasiswa();
        maha.setNama_mhs(nama_lengkap.getString());
        maha.setTempat_lahir(tempat_lahir.getString());
        maha.setTanggal_lahir(tanggal_lahir.getString());
        maha.setAgama(agama.getString());
        maha.setKelamin(kelamin.getString());
        maha.setAlamat_asal(alamat_asal.getString());
        maha.setKab_kota_asal(kabupaten.getString());
        maha.setProv_asal(provinsi.getString());
        maha.setNo_hp_mhs(no_telp.getString());
        maha.setNama_ayah(nama_ayah.getString());
        maha.setNama_ibu(nama_ibu.getString());
        maha.setPendidikan_ayah(pend_ayah.getString());
        maha.setPendidikan_ibu(pend_ibu.getString());
        maha.setPekerjaan_ayah(pekerjaan_ayah.getString());
        maha.setPekerjaan_ibu(pekerjaan_ibu.getString());
        maha.setPendapatan_ortu(pendapatan_ortu.getString());
        maha.setNo_tel_ortu(no_telp_rumah.getString());
        maha.setNo_hp_ortu(no_telp_hp.getString());
        maha.setAlamat_keluarga(alamat_keluarga_terdekat.getString());
        maha.setNo_tel_keluarga(no_telp_rumah_terdekat.getString());
        maha.setNo_hp_keluarga(no_telp_hp_terdekat.getString());
        maha.setNim(nim.getString());

        AkademikSR asr = new AkademikSR();
        asr.setProdi(prodi.getString());
        asr.setIpk_masuk(ipk_sr.getString());
        asr.setSemester(semester.getString());
        asr.setJurusan(jurusan.getString());
        asr.setFakultas(fakultas.getString());
        asr.setRapor_smu(rapor_smu.getString());
        asr.setNim(nim.getString());
        mhs.insertBiodata(maha, asr, foto, prestasi);
    } catch (FileUploadException ex) {
        System.out.println(ex.getMessage());
    }
    return "redirect:/mahasiswa/daftar";
}